首页 文章

belongsTo关系返回null

提问于
浏览
2

我有一个名为 Locins (位置)的表,它有一个外键到另一个名为 Rgn (区域)的表 .

所以在我的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_dumped它) .

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

表结构:

Locins表:[Locin_id(主键),RgnID(外键),其他不相关的字段] .

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

我究竟做错了什么?

edit 事实证明,DB中的愚蠢种子有一个不存在的条目的外键 . 我厌倦了陷入愚蠢的事情 . 对不起,祝你有个愉快的一天 .

3 回答

  • 0

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

    \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
    
  • 1

    您已为每个关系将两个关系列都设置为“RgnID” . 我猜它应该是别的东西 .

    记住它是:

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

    如果您通过位置模型获取区域,那么您应该使用相关模型的 eager loadinghttps://laravel.com/docs/5.2/eloquent-relationships#eager-loading

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

    希望这有助于您找到一个非常快速的解决方案 .

相关问题