Laravel - 当找不到关系时,用空数组替换null

时间:2017-05-03 08:04:00

标签: php eloquent laravel-5.4 laravel-eloquent laravel-collection

当找不到关系时,是否可以用空数组替换null?

E.g。客户有联系人和合同,但其中一个合同没有网络。

$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 []
    ]
  ]
]

当我在文档(Constraining Eager Loads)中阅读时,只能通过约束预先加载来操纵查询。

更新

合同类

class Contract extends Model
{
    public function web()
    {
        return $this->hasOne(Web::class);
    }
}

1 个答案:

答案 0 :(得分:0)

你的关系方法应该是处理这种关系的方法,因为它是你可以解决这个问题的第一个地方

我检查了这个,所以当变量为null时它会返回一个数组。

<td th:utext="${Comment}" th:remove="tag" >message ...</td>