嘿伙计们,我有一个令人困惑的问题
我有3张 table
- basket_lists(购物车)
- 购物篮项目 (carts_item)
- 产品
通过此迁移
'basket_lists':
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->boolean('active');
$table->timestamps();
basket_items:
$table->bigIncrements('id');
$table->unsignedBigInteger('product_Id');
$table->unsignedBigInteger('basket_list_id');
$table->timestamps();
products:
$table->bigIncrements('id');
$table->string('title');
$table->text('description');
$table->bigInteger('amount');
$table->timestamps();
当我搜索(查询)时,我的表格中有一些产品{
BasketList::where('active', '=', 1)->with('basketItems.products')->get();
它只给我第一个购物篮产品(其中 id = 1) 如果我插入新的购物篮列表并将第一个购物篮列表设置为 (active = 0),将第二个购物篮列表设置为 (active = 1),它将不会显示任何产品。
这是我的模型类:
class BasketList extends Model
{
public function basketItems()
{
return $this->hasMany(BasketItem::class ,'basket_list_id' );
}
}
class BasketItem extends Model
{
public function products()
{
return $this->hasMany(Product::class,'id' );
}
public function basketList()
{
return $this->belongsTo(BasketList::class);
}
}
public function basketItem()
{
return $this->belongsTo(BasketItem::class ,'product_id');
}
最佳答案
您必须更改与belongsTo()的关系
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BasketItem extends Model
{
//
protected $table = 'basket_items';
public function product()
{
return $this->belongsTo(Product::class, 'product_id','id' ); // Watch out for the case sensitive. how did you wright product_id in your migration. (product_id or product_Id)
}
关于php - eloquent 只获取第一个 Active 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60351284/