我在预先加载时遇到问题
我有两个模型:
class Provider extends Model
{
/**
* Get the currency record associated with the provider.
*/
public function currency()
{
return $this->hasOne('AppCurrency', 'tabcur', 'poucur')->where('tabcol','$DEV');
}
class Currency extends Model
{
/**
* Get the providers record associated with the currency.
*/
public function provider()
{
return $this->belongsTo('AppProvider', 'tabcur', 'poucur');
}
当我尝试这个时:
Provider::first()->currency
它的作品
但是,如果我尝试这个:
Provider::with('currency')->first()
字段货币为空
currency: null,
谁能帮我?
编辑 1
我试过这个
>>> DB::connection()->enableQueryLog()
>>> AppProvider::with('currency')->first()
>>> DB::getQueryLog()
我有这个与应用程序\提供者::与('货币'(->第一((
[
[
"query" => "select * from PROVIDER FETCH FIRST 1 ROWS ONLY",
"bindings" => [],
"time" => 18.74,
],
[
"query" => "select * from CURRENCY where tabcol = ? and CURRENCY.tabcur in (?)",
"bindings" => [
"$DEV",
" ",
],
"time" => 33.94,
],
]
但它是钢"空">
first()
做的是:
first
方法返回集合中通过给定真值检验的第一个元素。
因此,当通过 Eager 加载测试时,它将返回>第一条记录<<并加载关系。
但
您的关系currency
返回为空,因为您的货币关系中的where
条件未传递,因此它将显示关系已加载with
但不会显示任何记录,因为它没有通过where
。
发生这种情况是因为满足with
条件的第一条记录没有通过 where 条件,尝试删除where
然后再次加载关系并查看tabcol
的值是多少,然后再次执行此操作,但这次是where
但放置您为该返回的记录找到的值,它应该可以工作。
Provider::first()->currency
将返回一个Currency::class
Provider::with('currency')->first()
将返回一个 Provider::class 在关系 []中带有 Currency::class
我看不出您的代码不起作用的任何原因。