Laravel在多对多的关系中

时间:2016-05-10 20:07:53

标签: php laravel eloquent many-to-many relationships

我有两个主表,其中包含多对多关系和一个数据透视表。

型号'输入'

    public function attributes()
    {
        return $this->belongsToMany('App\Attribute', 'attribute_type');
    }

模型'属性'

    public function types()
    {
        return $this->belongsToMany('App\Type', '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');
    });

我希望以随机顺序显示属于id<类型的5个属性。 10。

$attributes = Attribute::whereHas('types', function ($query) {
            $query->where('id', '<', '10');
        })->orderByRaw("RAND()")->limit(5);

,例如

$attribute->id

给我&#34; Undefined属性:Illuminate \ Database \ Eloquent \ Builder :: $ id&#34;

2 个答案:

答案 0 :(得分:2)

您所要做的就是执行查询并使用$attribute方法获取集合,如下所示:

protected $casts = [
    'id' => 'integer',
    'courses.pivot.course_id' => 'integer',
    'courses.pivot.active' => 'boolean'
]

现在您正在尝试遍历查询构建器,该构建器为{{1}}

提供了另一个查询构建器

答案 1 :(得分:1)

您有两个选择:

$attributes = Attribute::whereHas('types', function ($query) {
            $query->where('types.id', '<', '10');
        })->orderByRaw("RAND()")->limit(5);

$attributes = Attribute::whereHas('types', function ($query) {
            $query->where('attribute_type.type_id', '<', '10');
        })->orderByRaw("RAND()")->limit(5);
相关问题