Laravel whereHas on Many-to-Many 关系

Posted

技术标签:

【中文标题】Laravel whereHas on Many-to-Many 关系【英文标题】:Laravel whereHas on Many-to-Many relationships 【发布时间】:2016-09-05 23:46:48 【问题描述】:

我有两个具有多对多关系的主表和一个数据透视表。

模型“类型”

    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');
    );

我想以随机顺序显示 5 个属于 id

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

例如

$attribute->id

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

【问题讨论】:

【参考方案1】:

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

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

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

【讨论】:

我也改变了 where('id', ' 【参考方案2】:

你有两个选择:

$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);

【讨论】:

虽然这可能会回答问题,但如果可能的话,您应该 edit 您的回答包含对如何这些陈述中的每一个回答问题的简短说明。这有助于提供上下文,并使您的答案对未来的读者更有用。

以上是关于Laravel whereHas on Many-to-Many 关系的主要内容,如果未能解决你的问题,请参考以下文章