Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel whereHas on Many-to-Many relationships

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"

like image 674
Estern Avatar asked May 10 '16 20:05

Estern


People also ask

What is the use of whereHas in Laravel?

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

How do you retrieve a many to many relationship?

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.

Does Laravel have many through relations?

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.


1 Answers

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

like image 91
Filip Koblański Avatar answered Sep 19 '22 11:09

Filip Koblański