本文介紹了Eloquent - Eager 加載關系的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我想弄清楚如何從相關表中預先加載數據.我有 2 個模型 Group
和 GroupTextPost
.
I'm trying to figure out how to eager load data from a related table. I have 2 models Group
and GroupTextPost
.
Group.php
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class Group extends Model
{
protected $table = 'group';
public function type()
{
return $this->hasOne('AppModelsGroupType');
}
public function user()
{
return $this->belongsTo('AppModelsUser');
}
public function messages()
{
return $this->hasMany('AppModelsGroupTextPost');
}
}
GroupTextPost.php
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class GroupTextPost extends Model
{
protected $table = 'group_text_post';
public function user()
{
return $this->belongsTo('AppModelsUser');
}
public function group()
{
return $this->belongsTo('AppModelsGroup');
}
}
我想要做的是在獲取群組文本帖子時預先加載 user
,以便在我提取消息時包含用戶名.
What I'm trying to do is eager load the user
when fetching group text posts so that when I pull the messages the user's name is included.
我試過這樣做:
public function messages()
{
return $this->hasMany('AppModelsGroupTextPost')->with('user');
}
...并像這樣調用:
$group = Group::find($groupID);
$group->messages[0]->firstname
但我收到一個錯誤:
Unhandled Exception: Call to undefined method IlluminateDatabaseQueryBuilder::firstname()
這可能與 Eloquent 相關嗎?
Is this possible to do with Eloquent?
推薦答案
你不應該直接在關系上預先加載.您可以始終在 GroupTextPost 模型上預先加載用戶.
You should not eager load directly on the relationship. You could eager load the user always on the GroupTextPost model.
GroupTextPost.php
GroupTextPost.php
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class GroupTextPost extends Model
{
protected $table = 'group_text_post';
/**
* The relations to eager load on every query.
*
* @var array
*/
protected $with = ['user'];
public function user()
{
return $this->belongsTo('AppModelsUser');
}
public function group()
{
return $this->belongsTo('AppModelsGroup');
}
}
或者你可以使用嵌套急切加載
$group = Group::with(['messages.user'])->find($groupID);
$group->messages[0]->user->firstname
這篇關于Eloquent - Eager 加載關系的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!