【问题标题】:Laravel: Same table, One-to-One relationshipLaravel:同一张表,一对一的关系
【发布时间】:2019-04-30 01:19:45
【问题描述】:

我有一个带有配偶字段的客户表,我正在引用该外键:

$table->integer('spouse')->nullable();
$table->foreign('spouse')->references('customerId')->on('customers');

我的问题是,如果我只能有一个名为 spouse() 的函数,我该如何设置函数以返回 belongsTo()hasOne()

public function spouse()
{
    return $this->hasOne('App\Customer');
}

谢谢。

【问题讨论】:

    标签: php sql laravel eloquent


    【解决方案1】:

    您只需要定义一个函数:

    # Customer.php
    
    public function spouse()
    {
        return $this->hasOne('App\Customer');
    }
    

    然后,当链接对象时,将对象相互关联

    # CustomersController.php
    
    $person_a = Customer::find(1);
    $person_b = Customer::find(2);
    $person_a->spouse()->save($person_b);
    $person_b->spouse()->save($person_a);
    

    然后使用它:

    # CustomersController.php
    
    $person_a = Customer::find(1);
    $person_b = $person_a->spouse;
    $person_a = $person_b->spouse;
    

    观察

    当使用不同于{model}_id的外键定义关系时,需要在定义关系时指定(查看docs):

    # Customer.php
    
    public function spouse()
    {
        return $this->hasOne('App\Customer', 'spouse');
    }
    

    另外,这个外键列需要是unsignedInteger()(如果主键是integer)或bigUnsignedInteger(),如果外键是bigInteger

    如果:

    $table->increments('customerId');
    

    做:

    $table->unsignedInteger('spouse')->nullable();
    $table->foreign('spouse')->references('customerId')->on('customers');
    

    或者,如果:

    $table->bigIncrements('customerId');
    

    做:

    $table->unsignedBigInteger('spouse')->nullable();
    $table->foreign('spouse')->references('customerId')->on('customers');
    

    【讨论】:

      猜你喜欢
      • 2020-02-21
      • 2019-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-04
      • 1970-01-01
      • 2011-10-04
      • 2012-11-10
      相关资源
      最近更新 更多