belongsTo关系返回null


belongsTo relationship returns null

我有一个名为Locins(locations)的表,它有一个指向另一个称为Rgn(regions)的表的外键。

所以在我的Locin模型中:

class Locin extends Model
{
    protected $table = 'Locin';
    protected $primaryKey = 'Locin_id';
    public $timestamps = false;
    public function Rgn()
    {
        return $this->belongsTo('App'Models'Rgn', 'RgnID', 'RgnID');
    }
}

在我的Rgn模型中:

class Rgn extends Model
{
    protected $table = 'Rgns';
    protected $primaryKey = 'RgnID';
    public $timestamps = false;
    public function Locin()
    {
        return $this->hasOne('App'Models'Locin', 'RgnID', 'RgnID');
    }
}

当我说:$location = Locin::find($request->Locin);一个位置成功返回。(我用var_dump)。

但是当我说$location->Rgn时,它返回null。

表格结构:

Locins表:[Locin_id(主键)、RgnID(外键)、其他不相关字段]。

Rgns表:[RgnID(主键),其他不相关字段]

我做错了什么?

编辑事实证明,DB中愚蠢的种子有一个不存在的条目的外键。我厌倦了老是做傻事。抱歉,祝你今天愉快。

您可以看到该区域正在运行的查询,这是测试流程的一种方式:

'DB::connection()->enableQueryLog();
$location = Locin::find(1);
$region = $location->Rgn;
$query = 'DB::getQueryLog();
$lastQuery = end($query);
dd($lastQuery);

你会得到类似的东西

array:3 [
    "query" => "select * from `Rgns` where `Rgns`.`RgnID` = ? limit 1"
    "bindings" => array:1 [▼
        0 => 1
    ]
    "time" => 0.5
]

替换查询中bindings的值,您可以直接将输出运行到数据库,以查看查询是否正确

Select * from `Rgns` where `Rgns`.`RgnID` = 1 limit 1

您已经为每个关系将两个关系列都设置为"RgnID"。我猜应该是别的东西。

记住:

return $this->belongsTo('App'Whatever', 'foreign_key', 'other_key');

如果要通过位置模型获取区域,则应使用热切加载(https://laravel.com/docs/5.2/eloquent-relationships#eager-加载)

$location = Locin::where('Locin_id', $request->Locin)->with('Rgn')->get();

希望这能帮助你找到一个非常快速的解决方案。