当没有找到关系时,是否可以用空数组替换 null ?
例如,客户有联系人和合同,但其中一个合同没有网络。
$customers = Customer::with('contacts', 'contracts.web')
->orderBy('company')->orderBy('prename')->get();
结果将如下...
2 => array:21 [
"id" => 1
"contacts" => array:2 [
0 => array:12 [
"id" => 1
"customer_id" => 1
]
1 => array:12 [
"id" => 2
"customer_id" => 1
]
]
"contracts" => array:2 [
0 => array:9 [
"id" => 1
"customer_id" => 1
"web" => array:7 [
"id" => 1
"contract_id" => 1
]
]
1 => array:9 [
"id" => 2
"customer_id" => 1
"web" => null // should be replaced with []
]
]
]
正如我在文档(约束急切负载)中所读到的,只能通过约束急切负载来操作查询。
更新
合同类
class Contract extends Model
{
public function web()
{
return $this->hasOne(Web::class);
}
}