Laravel 连接表以获取每个表的属性
Posted
技术标签:
【中文标题】Laravel 连接表以获取每个表的属性【英文标题】:Laravel join tables to get attribute from each one 【发布时间】:2020-03-27 22:21:59 【问题描述】:我有这 3 个表:
warehouses: id | warehouse_name
good_quantities: id | good_id | warehouse_id | quantity
goods: id | good_name
我正在尝试以大量获取所有记录,并希望在 View 中显示它,如下所示:
good_name | warehouse_name | quantity |
使用 Eloquent 获得此结果的正确查询是什么?
好模特
class Good extends Model
/**
* Get the Good Quantity for this Good.
*/
public function good_quantities()
return $this->hasMany('App\Models\Good_Quantity','good_id');
仓库模型
class Warehouse extends Model
/**
* Get the Goods Quantity for this Warehouse.
*/
public function good_quantities()
return $this->hasMany('App\Models\Good_Quantity','warehouse_id');
Good_Quantity 模型
class Good_Quantity extends Model
/**
* Get the Good's Info.
*/
public function good()
return $this->belongsTo('App\Models\Good','good_id');
/**
* Get the Good Quantity's Warehouse.
*/
public function warehouse()
return $this->belongsTo('App\Models\Warehouse','warehouse_id');
【问题讨论】:
首先,仓库和货物可以使用belongsToMany 了解多对多关系:laravel.com/docs/master/eloquent-relationships#many-to-many 【参考方案1】://you can get by using join
//in good model
function function_name()
$data=App\Good::join('good_quantities','good_quantities.good_id','=','good.good_id')
->join('warehouses','warehouses.warehouse_id','=','good_quantities.warehouse_id')
->select('good_name','warehouse_name','quantity')->get();
【讨论】:
以上是关于Laravel 连接表以获取每个表的属性的主要内容,如果未能解决你的问题,请参考以下文章