【问题标题】:Eager Loading return null in Laravel急切加载在 Laravel 中返​​回 null
【发布时间】:2020-10-23 21:53:59
【问题描述】:

我遇到了急切加载问题

我有两个模型:

class Provider extends Model
{
    /**
     * Get the currency record associated with the provider.
     */
    public function currency()
    {
        return $this->hasOne('App\Currency', 'tabcur', 'poucur')->where('tabcol','$DEV');
    }

class Currency extends Model
{
    /**
     * Get the providers record associated with the currency.
     */
    public function provider()
    {
        return $this->belongsTo('App\Provider', 'tabcur', 'poucur');
    }

当我尝试这个时:

Provider::first()->currency

成功了

但是,如果我尝试这个:

Provider::with('currency')->first()

字段货币为空

currency: null,

谁能帮帮我?

编辑 1

我试过了

>>> DB::connection()->enableQueryLog()

>>> App\Provider::with('currency')->first()

>>> DB::getQueryLog()

我有这个 App\Provider::with('currency')->first()

   [
     [
       "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,
     ],
   ]

但它是钢铁“空”

【问题讨论】:

  • 您的 Provider 表中有 currency 列吗?如果是,则更改关系名称。
  • 不,我的提供者表中没有“货币”列

标签: laravel eager-loading


【解决方案1】:

first()所做的是:

first 方法返回集合中通过给定真值测试的第一个元素。

所以当 Eager loading test 被通过时,它返回 >>First Record

但是

您的关系currency 返回空,因为您的货币关系中的where 条件未通过,因此它将显示该关系已加载with,但它不会显示任何记录,因为它没有t 传递where。

这是因为第一个满足with条件的记录没有通过where条件,尝试删除where然后再次加载关系,看看tabcol的值是什么,然后再做一次但这次使用where,但输入您为该返回记录找到的值,它应该可以工作。

【讨论】:

  • 我删除了模型中的where 条件,放入tabcol 的新值并尝试使用新值,但字段货币仍然null
【解决方案2】:

Provider::first()->currency 将返回一个 Currency::class

Provider::with('currency')->first() 将返回一个 Provider::class 与 Currency::class 在 relations[]

我看不出您的代码无法运行的任何原因。

【讨论】:

  • 它在 ISO-8859-15 中编码的数据库,可能是问题?
猜你喜欢
  • 2020-09-12
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-13
  • 2021-04-23
相关资源
最近更新 更多