[英]Slim 3 with Eloquent ORM - Relationships not exist on collection
我的基於 Slim 3 的應用程序中的 Eloquent 關系有問題。 目標是返回 $data 以查看。 當我嘗試這樣做時:
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;
我收到錯誤消息:此集合實例上不存在屬性 [offer]。 我在我的報價和收藏模型中建立了關系:
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');
}
在數據庫中,我們可以看到表:offer(帶有 url 列)和收藏夾(帶有 offer_url 列)。
如何使這種關系發揮作用?
請幫忙。
Get 方法返回一個 Collection 實例,而不是 Favorite。
用:
$favs = F::where('user_id', $_SESSION['user_id'])->get();
然后:
foreach($favs as $favorite) {
$offer = $favorite->offer;
}
並且不要忘記使用eager loader: https : //laravel.com/docs/5.4/eloquent-relationships#lazy-eager-loading
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.