Laravel Eloquent 映射数据与关系

发布于 2025-01-13 22:28:38 字数 744 浏览 3 评论 0原文

我有一个带有关系的雄辩查询,但我得到 ErrorException: Trying to get property '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);

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

I have an eloquent query with a relation but I get ErrorException: Trying to get property '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);

Is there any way to use eloquent mapping with relation?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吹泡泡o 2025-01-20 22:28:38

使用 Laravel 的辅助方法:
可选()

可选函数接受任何参数并允许您访问
属性或调用该对象的方法。如果给定的对象是
null,属性和方法将返回 null 而不是导致
错误:

而不是:

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

使用这个:

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

Use Laravel's helper method:
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:

Instead of:

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

Use this:

// ...
                        'id' => optional($contact->shop)->id, ✅
                        'name' => optional($contact->shop)->name ✅
// ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文