【问题标题】:Laravel relationship, one database has two foreign keysLaravel关系,一个数据库有两个外键
【发布时间】:2017-09-15 19:51:30
【问题描述】:

这是我的位置表:

ID
Name
Type

这是Routes表:

ID
Location_start(int)
Location_distination(int)
Distance
Rate

我尝试在这两个表之间建立关系,因此我可以在 foreach 循环中获取location_startlocation_distination 的位置名称。我试过了:

public function locationStart()
{
$this->belongsTo('App\Route', 'location_start');
}
public function locationDistination()
{
$this->belongsTo('App\Route', 'location_distination');
}

但它并没有以这种方式工作。

【问题讨论】:

  • 请 a) 告诉我们哪些列(如果有)是外键以及它们引用的内容 b) 您将此(发布的关系)放入哪个模型中。
  • 尝试使用hasOne 而不是belongsTo
  • @devk Location_start 和 Location_distination.在位置模型中
  • 然后只需将->belongsTo('App\Route', 'location_start') 更改为->hasMany('App\Route', 'location_start')。 loc_end 也一样。您定义了逆向(您将在 Route 模型中使用 belongsTo,因为 routes 表具有外键(因此“属于”)。
  • 看看这个答案stackoverflow.com/a/25061868/4668162 ,确保您的迁移或表构造正确

标签: database laravel foreign-keys relationship


【解决方案1】:

您的路线类应如下所示:

class Route extends Model
{
    public function locationStart()
    {
        $this->belongsTo(Location::class, 'location_start');
    }

    public function locationDestination()
    {
        $this->belongsTo(Location::class, 'location_distination');
    }
}

那么你应该可以做到:

$route = Route::with('locationStart', 'locationDestination')->find(20);
$route->locationStart->Name;
$route->locationEnd->Name;

【讨论】:

    猜你喜欢
    • 2020-10-04
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    • 2013-03-16
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 2020-06-30
    相关资源
    最近更新 更多