我收集了Laravel 5.1中的热切加载。我知道有一种方法可以帮助我获取特定列的列表。但我需要在我的超级系列中找到最后的关系。
以下代码帮助我获取办公室的路线,路线客户和客户的信用。
$offices = Office::with( 'routes.customers.creditos' )->where( 'user_id', '=', $user->id )->get();
返回以下(数组格式):
array:1 [
0 => array:10 [
"id" => 10
...
"routes" => array:2 [
0 => array:10 [
"id" => 1
...
"customers" => array:2 [
0 => array:21 [
"id" => 1
...
"creditos" => array:1 [
"id" => 1
...
]
]
]
]
我只需要回报学分:
$creditos = $offices->lists( 'routes.customers.creditos' )->all();
它不起作用,似乎lists()方法只获取第一级的列......
答案 0 :(得分:1)
有(至少)2个选项:
选项1:
$offices = Office::with( 'routes.customers.creditos' )->where( 'user_id', '=', $user->id )->get();
$creditos = array();
$offices->routes->map(function($route) use ($creditos) {
$route->customers->map(function($customer) use ($creditos) {
$creditos = array_merge($creditos, $customer->creditos->all());
});
});
选项2:
$creditos = Credit::join('customers', 'creditos.customer_id', '=', 'customers.id')
->join('routes', 'customers.route_id', '=', 'routes.id')
->join('offices', 'routes.office_id', '=', 'offices.id')
->where('offices.user_id', '=', $user_id)
->get();