I have two main tables with relationships many to many and a pivot table.
Model 'Type'
public function attributes()
{
return $this->belongsToMany('App\Attribute', 'attribute_type');
}
Model 'Attribute'
public function types()
{
return $this->belongsToMany('App\Type', 'attribute_type');
}
Pivot table 'attribute_type'
Schema::create('attribute_type', function (Blueprint $table) {
$table->increments('id');
$table->integer('type_id')->unsigned();
$table->foreign('type_id')->references('id')->on('types');
$table->integer('attribute_id')->unsigned();
$table->foreign('attribute_id')->references('id')->on('attributes');
});
I want to show 5 attributes in random order which belong to the types of id < 10.
$attributes = Attribute::whereHas('types', function ($query) {
$query->where('id', '<', '10');
})->orderByRaw("RAND()")->limit(5);
and for example
$attribute->id
gives me "Undefined property: Illuminate\Database\Eloquent\Builder::$id"
whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.
To avoid this problem, you can break the many-to-many relationship into two one-to-many relationships by using a third table, called a join table. Each record in a join table includes a match field that contains the value of the primary keys of the two tables it joins.
Eloquent Relationships is one of the most useful and powerful features of the Laravel Framework. It is one of the reasons why I like Laravel most. Mainly it helps us to fetch or insert data in a very easy and efficient way.
All you have to do is execute query and get the collection with get()
method like this:
$attributes = Attribute::whereHas('types', function ($query) {
$query->where('id', '<', '10');
})->orderByRaw("RAND()")->limit(5)
->get();
Now you are trying to iterate over the query builder which is giving you another query builder as a result of $attribute
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With