Laravel whereHas 多对多关系

Laravel whereHas on Many-to-Many relationships

我有两个主要 table 具有多对多关系和一个枢轴 table。

型号'Type'

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

型号'Attribute'

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

旋转 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');
    });

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

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

例如

$attribute->id

给我 "Undefined property: Illuminate\Database\Eloquent\Builder::$id"

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

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

现在您正尝试遍历查询生成器,由于 $attribute

,它为您提供了另一个查询生成器

您有 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);