Laravel 引用外键数据
Posted
技术标签:
【中文标题】Laravel 引用外键数据【英文标题】:Laravel Referencing Foreign Key Data 【发布时间】:2015-07-07 08:46:30 【问题描述】:菜鸟问题传入..
$data = DB::table('fquotes')->orderBy('created_at', 'DESC')->get();
我有这个查询,它从 fquotes 中提取所有数据。每个项目都有一个 cid,该 cid 链接到另一个表中的客户 ID。如何从客户表中包含与提取的每一行匹配的列(名称)?
我要显示数据:
客户行中的客户名称 - fquotes 行
【问题讨论】:
【参考方案1】:不用加入也可以使用,只用一个foreach
public function index(Request $request, $id)
$items = ReportGlAssignment::where('shop_id', $id)->paginate(10);
foreach ($items as $item )
$bill = BillingAssignment::where('id',$item->billing_assignment_id )->pluck('assignment');
$item['billing_assignment_id'] = $bill;
return response()->json($items);
它会显示你的外键数据的名称,
id: 7,
designation: "Food Service",
income_gl: "333",
expense_gl: "333",
billing_assignment_id: "bgjjnhkj",
shop_id: 12,
created_at: "2017-08-21 07:26:48",
updated_at: "2017-08-23 09:35:54"
,
【讨论】:
【参考方案2】:在调用get()
将执行查询之前,调用join()
方法,它将通过指定列将您的表连接到另一个表。
$data = DB::table('fquotes')
->select('customers.id as customer_id', 'fquotes.id as fquotes_id', DB::raw('*'))
->orderBy('created_at', 'DESC')
->join('customers', 'fquotes.cid', '=', 'customers.id')
->get();
【讨论】:
谢谢!它通常是每个人都应该知道的最基本的 php 东西,但很难找到答案,因为它是如此简单.. :) 我遇到了另一个问题。客户的 ID 覆盖了返回对象中 fquotes 的 ID。有什么想法吗? 是的,你可以在选择中给它们起别名,我已经更新了答案。以上是关于Laravel 引用外键数据的主要内容,如果未能解决你的问题,请参考以下文章