简体   繁体   English

带有 Eloquent ORM 的 Slim 3 - 集合中不存在关系

[英]Slim 3 with Eloquent ORM - Relationships not exist on collection

I have a problem with Eloquent relationships in my Slim 3 based application.我的基于 Slim 3 的应用程序中的 Eloquent 关系有问题。 The goal is return $data to view.目标是返回 $data 以查看。 When I try that:当我尝试这样做时:

use App\Models\Favorite as F;
$favs = F::where('user_id',$_SESSION['user_id'])->get()->offer;

foreach($favs as $offer)
{
    //  not important now...
}

return $data;       

I am getting an error: Property [offer] does not exist on this collection instance.我收到错误消息:此集合实例上不存在属性 [offer]。 I made relations in my Offer and Favorite models:我在我的报价和收藏模型中建立了关系:

public function offer() // in Favorite model
{
    return $this->belongsTo('App\Models\Offer', 'offer_url');
}

public function favorite() // in Offer model
{
    return $this->hasMany('App\Models\Favorite', 'url');
}

In database we can see tables: offers (with url column) and favorites (with offer_url column).在数据库中,我们可以看到表:offer(带有 url 列)和收藏夹(带有 offer_url 列)。

How to make that relationships working?如何使这种关系发挥作用?

Please for help.请帮忙。

Get method return a Collection instance, not Favorite. Get 方法返回一个 Collection 实例,而不是 Favorite。

Use:用:

$favs = F::where('user_id', $_SESSION['user_id'])->get();

then:然后:

foreach($favs as $favorite) {
   $offer = $favorite->offer;
}

And don't forget to use eager loader: https://laravel.com/docs/5.4/eloquent-relationships#lazy-eager-loading并且不要忘记使用eager loader: https : //laravel.com/docs/5.4/eloquent-relationships#lazy-eager-loading

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

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