Laravel Eloquent 映射数据与关系

Laravel Eloquent mapping data with relationship

我有一个带有关系的 eloquent 查询,但我得到 ErrorException: Trying to get 属性 'id' of shop->id.

    $collection = Lead::with('shop');
    $collection = $collection->orderBy('data', 'DESC');
    $collection = $collection->get();
    
        $json = $collection->map(function ($contact) {
                    return [ 
                     'id' => $contact->id,
                     'name' => $contact->name,
                     'shop' => [
                        'id' => $contact->shop->id,
                        'name' => $contact->shop->name
                      ],
                ];
        });

 return response()->json(['contacts' => $json], 200);

有什么方法可以使用 eloquent 关系映射吗?

使用Laravel的辅助方法: optional()

The optional function accepts any argument and allows you to access properties or call methods on that object. If the given object is null, properties and methods will return null instead of causing an error:

而不是:

// ...
                        'id' => $contact->shop->id,
                        'name' => $contact->shop->name
// ...

使用这个:

// ...
                        'id' => optional($contact->shop)->id, ✅
                        'name' => optional($contact->shop)->name ✅
// ...