Php Laravel拥有多对多关系
我有两个具有多对多关系的主表和一个透视表 模型“类型”Php Laravel拥有多对多关系,php,laravel,eloquent,many-to-many,relationships,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', 'attribut
public function attributes()
{
return $this->belongsToMany('App\Attribute', 'attribute_type');
}
模型“属性”
public function types()
{
return $this->belongsToMany('App\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<10的类型
$attributes = Attribute::whereHas('types', function ($query) {
$query->where('id', '<', '10');
})->orderByRaw("RAND()")->limit(5);
给我“Undefined property:Illumb\Database\Eloquent\Builder::$id”您所要做的就是执行查询并使用下面的
get()
方法获取集合:
$attributes = Attribute::whereHas('types', function ($query) {
$query->where('id', '<', '10');
})->orderByRaw("RAND()")->limit(5)
->get();
$attributes=Attribute::whereHas('types',function($query){
$query->where('id','p>您有两个选项:
$attributes = Attribute::whereHas('types', function ($query) {
$query->where('types.id', '<', '10');
})->orderByRaw("RAND()")->limit(5);
$attributes=Attribute::whereHas('types',function($query){
$query->where('types.id',我也更改了where('id',),虽然这可能会回答问题,但如果可能的话,您应该在答案中包含一个简短的解释,说明这些语句如何回答问题。这有助于提供上下文,并使您的答案对未来的读者更有用。
$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);