gpt4 book ai didi

php - Laravel whereHas 的多对多关系

转载 作者:行者123 更新时间:2023-12-01 19:56:32 29 4
gpt4 key购买 nike

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

模型“类型”

    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 < 10 类型的 5 个属性。

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

例如

$attribute->id

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

最佳答案

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

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

现在,您正在尝试迭代查询构建器,这会由于 $attribute

为您提供另一个查询构建器

关于php - Laravel whereHas 的多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37148000/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com