Laravel whereHas 多对多关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37148000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:46:07  来源:igfitidea点击:

Laravel whereHas on Many-to-Many relationships

phplaraveleloquentmany-to-manyrelationships

提问by Estern

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'

数据透视表“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.

我想以随机顺序显示 5 个属于 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"

给我“未定义的属性:Illuminate\Database\Eloquent\Builder::$id”

回答by Filip Koblański

All you have to do is execute query and get the collection with get()method like this:

您所要做的就是执行查询并使用如下get()方法获取集合:

$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

现在您正在尝试迭代查询构建器,它为您提供另一个查询构建器作为结果 $attribute