laravel数据表关系 [英] laravel datatable relationships
本文介绍了laravel数据表关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此在此应用程序Drawing
belongsTo
Customer
中.我有数据表
So in this app Drawing
belongsTo
Customer
. I have datatable
<table id='drawing-table' class="table table-bordered table-hover">
<thead>
<tr>
<th>Drawing number</th>
<th>Customer</th>
</tr>
</thead>
</table>
表示$darwing->number
和$customer->title
.要加载信息我use yajra\Datatables\Datatables;
.
which indicates $darwing->number
and $customer->title
. To load info I use yajra\Datatables\Datatables;
.
使用此JS方法加载数据:
Data is loaded with this JS method:
$(function () {
$('#drawing-table').DataTable({
processing: true,
serverSide: true,
ajax: '{{route('drawings.datatable')}}',
columns: [
{ data: 'number', name: 'number' },
{ data: 'customer.title', name: 'customer' },
]
});
});
这个Laravel方法:
And this Laravel method:
public function datatable()
{
$drawings = Drawing::select(array('drawings.id','drawings.number'));
return Datatables::of(Drawing::with('customer')->select('*'))->make(true);
}
问题
- 如何使数据表搜索窗口与
$customer->title
一起使用? - 如何显示工程图编号和客户标题作为链接?
- How do I make datatable search window to work with
$customer->title
? - How do I display drawing number and customer title as link?
推荐答案
public function datatable()
{
//reference customer table
$drawings = DB::table('customers')
// join it with drawing table
->join('drawings', 'drawings.customer_id', '=', 'customers.id')
//select columns for new virtual table. ID columns must be renamed, because they have the same title
->select(['drawings.id AS drawing_id', 'drawings.number', 'customers.title', 'customers.id AS customer_id']);
// feed new virtual table to datatables and let it preform rest of the query (like, limit, skip, order etc.)
return Datatables::of($drawings)
->editColumn('title', function($drawings) {
return '<a href="'.route('customers.show', $drawings->customer_id).'">' . $drawings->title . '</a>';
})
->editColumn('number', function($drawings) {
return '<a href="'.route('drawings.show', $drawings->drawing_id).'">' . $drawings->number . '</a>';
})
->make(true);
}
花了很多小时试图弄清楚,希望它可以节省人的时间. http://datatables.yajrabox.com/fluent/joins
Spent many hours trying to figure it out, hope it saves someone time. http://datatables.yajrabox.com/fluent/joins
这篇关于laravel数据表关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文