Eloquent关系返回null,但类似的关系很好

时间:2017-10-20 12:39:50

标签: eloquent lumen laravel-eloquent

使用流明5.5.2并照亮/数据库v5.5.17。

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

与库的关系按预期工作,该区域返回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";

将回显软件仓库ID,该区域将导致错误,因为它不是对象。

将模型名称作为数组->with(['area', 'depot'])传递,或者只是请求区域(任一方法)都无法修复它。

Quote.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');
    }

}

Area.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');
    }

}

Depot.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)

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

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

1 个答案:

答案 0 :(得分:1)

因此,这个难题的缺失是,该项目是针对遗留数据库设置的,作为更新现有Web应用程序的一部分。

原来有一些数据类型不一致;当我成功地将另一个模型链接到区域而没有任何问题时,我发现了这一点。 area_id的字段通常是零填充的int,但由于某种原因,在引号表上它是一个char;因此,在浏览器中浏览时数据看起来是正确的,并且在复制和粘贴时工作,但在Eloquents内部的某处不匹配。

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

相关问题