Php 此集合实例上不存在Laravel 5 Eloquent join 2 table Get属性[tradeHistories]
我在这里遇到了一个问题,我不知道为什么会发生这种情况,因为我完全遵循了youtube上的教程 问题是: Account.phpPhp 此集合实例上不存在Laravel 5 Eloquent join 2 table Get属性[tradeHistories],php,laravel-5,eloquent,query-builder,laravel-eloquent,Php,Laravel 5,Eloquent,Query Builder,Laravel Eloquent,我在这里遇到了一个问题,我不知道为什么会发生这种情况,因为我完全遵循了youtube上的教程 问题是: Account.php #region Relationship: one to many public function tradeHistories() { return $this->hasMany('App\TradeHistory'); } #endregion #region Relationship: one to many (reversed) public f
#region Relationship: one to many
public function tradeHistories() {
return $this->hasMany('App\TradeHistory');
}
#endregion
#region Relationship: one to many (reversed)
public function account() {
return $this->belongsTo('App\Account');
}
#endregion
public function index()
{
$accounts = Account::all();
dd($accounts->tradeHistories);
return view('pages.account.index')
->with('active', 'account')
->with('accounts', $accounts);
}
TradeHistory.php
#region Relationship: one to many
public function tradeHistories() {
return $this->hasMany('App\TradeHistory');
}
#endregion
#region Relationship: one to many (reversed)
public function account() {
return $this->belongsTo('App\Account');
}
#endregion
public function index()
{
$accounts = Account::all();
dd($accounts->tradeHistories);
return view('pages.account.index')
->with('active', 'account')
->with('accounts', $accounts);
}
accountscocontroller.php
#region Relationship: one to many
public function tradeHistories() {
return $this->hasMany('App\TradeHistory');
}
#endregion
#region Relationship: one to many (reversed)
public function account() {
return $this->belongsTo('App\Account');
}
#endregion
public function index()
{
$accounts = Account::all();
dd($accounts->tradeHistories);
return view('pages.account.index')
->with('active', 'account')
->with('accounts', $accounts);
}
作为回报,我收到了这个消息
“此集合实例上不存在属性[tradeHistories]”
那我为什么要得到这个信息?因为我想显示所有账户的所有交易历史。这是因为
$accounts
是账户的集合,所以集合中的每个单独项目都可以访问交易历史。例如,第一项:
$accounts = Account::all();
dd($accounts->first()->tradeHistories);
或循环所有项目,每个项目都可以访问:
foreach ( $accounts as $account ) {
dd($account->tradeHistories);
}
我建议立即加载tradeHistories
,这样每个帐户项就不会进行额外的查询:$accounts=account::with('tradeHistories')->get()代码>试着给它括号我应该把它放在哪里?抱歉,我刚开始学习laravelif如果你是说tradeHistories()
,我已经尝试过了,我得到了这个“方法illumb\Database\elount\Collection::tradeHistories不存在”。你能运行php artisan缓存:clear或php artisan:optimize吗?并添加@rahulsm注释,他指的是\Account::all(),为了防止在我将这个$accounts=Account::with('tradeHistories')->get()放入后出现未定义的类
为什么它会给我一个类似于未知列“trade\u histories.account\u account\u number”的错误,因为字段列是account\u number
而不是account\u account\u number
@khrisnagunasurya您必须修改模型中的关系,因为您的表外键列与雄辩的约定不匹配。试试这个return$this->hasMany('App\TradeHistory','account_number')代码>或根据您的表列修改它。为什么我得到这个“此集合实例上不存在属性[phptradehistics]”?添加帐号字段后,我只是尝试添加$accounts的原始数据,为什么我会看到这个关系:[]
?因为我认为我应该看到一些关系,对吗?@khrisnagunasuryatradeHistories()
与一个账户相关$accounts
是许多帐户的集合,因此您需要一个帐户模型来访问与TradeHistory的关系。