我在两个表之间建立了多对多关系,在数据透视表与另一个表相关的同时,在数据透视表上具有id(主键)。
这是一个 ER Diagram
|Table Product |
|- id |
|- name |
|- price |
-----------------------
|Table Warehouse |
|- id |
|- location |
|- staff_id |
-----------------------
|Table Stock (Pivot) |
|- id |
|- product_id |
|- warehouse_id |
-----------------------
|Table Stock Movement |
|- id |
|- stock_id |
|- quantity |
|- description |
-----------------------
模型类
// Warehouse model
class Warehouse extends Model
{
public function products()
{
return $this->belongsToMany('App\Product', 'stocks')->using('App\Stock');
}
}
// Product model
class Product extends Model
{
public function warehouses()
{
return $this->belongsToMany('App\Warehouse', 'stocks')->using('App\Stock');
}
}
// Stock model, this is the pivot table.
// Note that it's not extends to laravel eloquent model anymore
class Stock extends Pivot
{
protected $table = 'stocks';
public function stock_movement()
{
return $this->hasMany('App\StockMovement');
}
}
// StockMovement model
class StockMovement extends Model
{
public function stock()
{
return $this->belongsTo('App\Stock');
}
}
如果我从产品模型中检索数据透视表,则我无法获取数据透视表ID。我想用它来检索股票模型
雄辩的查询:
$warehouses = Product::find($product_id)->warehouses;
return $warehouses;
JSON响应:
{
id: 1,
staff_id: 1,
created_at: "2018-07-02 13:40:20",
updated_at: "2018-07-02 13:40:20",
pivot: {
product_id: 1,
warehouse_id: 1
}
}
如何获取数据透视表ID?
我是否必须更改雄辩的查询?,
还是更改表之间的关系?
谢谢。
答案 0 :(得分:0)
您可以使用withPivot
来访问数据透视中的其他文件
class Stock extends Pivot
{
protected $table = 'stocks';
public function stock_movement()
{
return $this->hasMany('App\StockMovement')->withPivot('id');
}
}
现在您可以访问它
$warehouses = Product::find($product_id)->warehouses;
foreach($warehouses as $warehouse){
dd($warehouse->pivot->id);
}
注意:在数据透视表中定义关系不是一种好习惯,因为那样一来,您就无法立即加载该关系。如果您的数据透视表与第三个表有关系,那么更好的用户hasMany
和belongsTo
的关系。