简体   繁体   English

Laravel刀片嵌套属于关系访问

[英]Laravel Blade Nested BelongsTo Relationship access

I have a nested BelongsTo relationship in eloquent Laravel, when I try to access it one level its success, but when I try to access it two level. 我雄辩的Laravel中有一个嵌套的BelongsTo关系,当我尝试成功访问它的一个级别时,但是当我尝试访问它的两个级别时,则是如此。 its getting error "Trying to get property of non-object" 其获取错误“试图获取非对象的属性”

Here's my structure models 这是我的结构模型

OrderProduct.php OrderProduct.php

public function product()
{
    return $this->belongsTo('App\Models\Product');
}

Product.php Product.php

public function domain()
{
    return $this->belongsTo('App\Models\Domain');
}

What I want to do is getting domain information from order_product eloquent, and I did this on blade, but getting error "Trying to get property of non-object" 我想做的是雄辩地从order_product获取域信息,而我在刀片服务器上做到了,但是却收到错误消息“试图获取非对象的属性”

$order_product = OrderProduct::first();
$domain_name = $order_product->product->domain->name;

But when I have product eloquent and try to access the domain name, its success 但是当我精通产品并尝试访问域名时,它就成功了

$product = Product::first();
$domain_name = $product->domain->name;

What should I do to access domain relationship from order_product through product->domain relationship? 我应该怎么做才能通过product-> domain关系从order_product访问域关系?

Thanks 谢谢

The problem occures when you are fetching domain from product which doesn't have domain. 当您从没有域的产品中获取域时,就会发生此问题。 You can use laravel optional function: 您可以使用laravel可选功能:

$orderProduct = OrderProduct::with('product.domain')->first();
$domain_name = optional($orderProduct->product->domain)->name;

Note: I also use eager load to reduce queries. 注意:我也使用紧急负载来减少查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM