【问题标题】:Eloquent relationship returns null, but a similar one is fine雄辩的关系返回null,但类似的关系很好
【发布时间】:2017-10-20 12:39:50
【问题描述】:

使用 Lumen 5.5.2 和Illumination/database v5.5.17。

我设置了 3 个模型,其中一个属于另一个 2。所以 Quote,有一个区域和一个仓库。

与depot的关系按预期工作,区域返回null。

例如

    $quoteModel = new Quote();        
    $quote = $quoteModel
            ->with('area')
            ->with('depot')
            ->where('id', '=', $id)
            ->first();


    echo 'depot id : ' , $quote->depot->id , "<br>\n";
    echo 'area id : ' , $quote->area->id , "<br>\n";

depot id 将被回显,该区域将导致错误,因为它不是对象。

将模型名称作为数组 -&gt;with(['area', 'depot']) 传递,或者只是请求区域(任何一种方法)都不能解决问题。

引用.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model as EloquentModel;

class Quote extends EloquentModel {

    protected $table = 'quotes';

    public function area() {
        return $this->belongsTo('\App\Models\Area', 'area_id', 'id');
    }

    public function depot() {
        return $this->belongsTo('\App\Models\Depot', 'depot_id', 'id');
    }

}

区域.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model as EloquentModel;

class Area extends EloquentModel {

    protected $table = 'areas';

    public $timestamps = false;
    public $incrementing = false;

    public function quotes() {
        return $this->hasMany('\App\Models\Quote', 'area_id', 'id');
    }

}

仓库.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model as EloquentModel;

class Depot extends EloquentModel {

    protected $table = 'depots';

    public $timestamps = false;
    public $incrementing = false;

    public function quotes() {
        return $this->hasMany('\App\Models\Quote', 'depot_id', 'id');
    }

}

如果我在 Area.php 中创建解析错误,脚本将失败,证明它被包含在内。

我设置了一个侦听器,因此我可以记录查询,并且它们显示得很好。

select * from `quotes` where `id` = 99192 limit 1
select * from `areas` where `areas`.`id` in (072)
select * from `depots` where `depots`.`id` in (07)

如果我手动运行区域查询,它会返回我期望的行。

我尝试更改区域关系的名称,但没有帮助。

【问题讨论】:

  • 你用的是什么雄辩的版本?您可以尝试 ->with(['area', 'depot']) 而不是链接它们吗?
  • 感谢版本提醒。它们是撰写本文时的最新版本(我在 5.4 上,升级没有帮助或伤害) - 我已经更新了我的问题。可悲的是数组语法没有帮助

标签: eloquent lumen laravel-eloquent


【解决方案1】:

因此,难题中缺少的部分是,该项目是针对旧数据库设置的,作为更新现有网络应用程序的一部分。

原来存在一些数据类型不一致;当我可以成功地将另一个模型链接到没有问题的区域时,我发现了这一点。 area_id 的字段通常是一个零填充的 int,但由于某种原因在报价表上它是一个字符;因此在管理员中浏览时数据看起来正确,并且在复制和粘贴时有效,但在 Eloquents 内部的某个地方不匹配。

更改表的数据类型可以解决问题。

【讨论】:

  • 很高兴看到你想通了!
猜你喜欢
  • 2017-07-29
  • 2018-04-11
  • 1970-01-01
  • 2014-08-27
  • 2014-10-23
  • 2015-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多