Laravel对同一模型的多个hasOne的正确方法


Laravel proper approach to multiple hasOne for same model

我有一个具有以下架构的carriages表:

foreign: subsidiary_id
string: type
string: postal_code

还有一个subsidiaries表,具有以下体系结构:

string: name
string: internal_reference
decimal: expedition_rate

现在,我即将在子公司控制器中调整我的商店功能,以便它将自动为该新子公司创建 2 辆车厢。

我知道,在创建子公司后,我可以很容易地进行个人创建步骤,但我想知道,如何使用关系方式?

我所知道的是,在我的Subsidiary.php模型中,我可以创建 2 个函数,如下所示:

public function carriageExport()
{
    return $this->hasOne('Carriage');
}
public function carriageImport()
{
    return $this->hasOne('Carriage');
}

carriageExport将是一个carriages.type = 'export'carriageImport将是一个carriages.type = 'import'

所以

  1. 我无法弄清楚,如果定义关系函数是否正确完成。你觉得怎么样?我错过了什么,对吧?这是什么?
  2. 您是否愿意坚持使用非关系版本?
在这种情况下,

作用域是要走的路:

class Subsidiary extends Eloquent {
    public function carriage()
    {
        return $this->hasOne('Carriage');
    }
}
class Carriage extends Eloquent {
    public function scopeImport($query)
    {
        return $query->whereType('import');
    }
    public function scopeExport($query)
    {
        return $query->whereType('export');
    }
}

然后,您可以:

echo Subsidiary::find(1)->carriage()->import()->first()->postal_code;