Laravel 5.6 Eloquent 关系未返回值

Laravel 5.6 Eloquent Relationship not returning value

这是我在 Laravel

中的两个相关模型的一部分
class Employee extends Authenticatable
{
    use Notifiable;

    protected $primaryKey = 'employee_id';
    public $incrementing = false;

    public function branch(){
        return $this->belongsTo('App\Branch');
    }

    public function orders(){
        return $this->hasMany('App\Order');
    }
}

class Branch extends Model
{

    protected $primaryKey = 'branch_id';
    public $incrementing = false;

    public function employees(){
        return $this->hasMany('App\Employee');
    }
}

以上两个模型的迁移(仅up函数)

public function up()
{
    Schema::create('branches', function (Blueprint $table) {
        $table->string('branch_id')->unique();
        $table->timestamps();
        $table->primary('branch_id');
    });
}


public function up()
{
    Schema::create('employees', function (Blueprint $table) {     
        $table->string('employee_id')->unique();
        $table->string('name');
        $table->string('password');
        $table->string('job');
        $table->string('branch_id');
        $table->foreign('branch_id')->references('branch_id')->on('branches')->onDelete('cascade');          
        $table->rememberToken();
        $table->timestamps();
        $table->primary('employee_id');
    });
}

当我 运行 php artisan tinker 并测试关系时,我得到以下输出:

 >>> namespace App
 >>> $emp = new Employee()
 => App\Employee {#778}
 >>> $emp = $emp->find('CMB-EMP-001')
 => App\Employee {#787
     employee_id: "CMB-EMP-001",
     name: "FirstName LastName",
     job: "Root",
     branch_id: "CMB",
     created_at: "2018-04-11 17:24:53",
     updated_at: "2018-04-11 17:24:53",
   }
 >>> $emp->branch()->get()
 => Illuminate\Database\Eloquent\Collection {#775
     all: [],
    }

如您所见,它 returns 是一个空数组,而不是员工的分支 ID。我做错了什么?

编辑:

>>> $emp->branch
 => null

您必须指定外键:

class Employee extends Authenticatable
{
    public function branch(){
        return $this->belongsTo('App\Branch', 'branch_id');
    }
}

并使用 $emp->branch 而不是 $emp->branch()->get()

改变你们的belongsTo()关系

public function branch(){
    return $this->belongsTo('App\Branch', 'branch_id', 'branch_id');
}

以乔纳斯的观点为基础,并为未来的观众提供更清晰的信息:

定义 belongsTo 关系的实际签名是

belongsTo(relatedEntity, foreignKey, ownerKey, relationModel)

目前,在您使用 belongsTo 时,您只是在定义与哪个相关实体建立关系。您需要做的是提供所有者密钥(而不是外键)的详细信息,因此在您的情况下:

return $this->belongsTo('App\Branch', 'branch_id', 'branch_id');

为什么会这样?

Laravel 确定使用哪一列的默认行为是:

  1. 对于外键,取相关的实体名称并添加_id后缀。 IE。 branch_id
  2. 对于所有者键,默认使用 "id",因为 Laravel 的约定是模型的主键应称为 "id"。

鉴于您在迁移中修改了 Laravel 的默认方法,通过命名您的主键 "branch_id" 而不仅仅是 "id",您需要告诉 Laravel 如何关联这两个模型。