这是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');
}
}
这些是上述两种模型的迁移(仅向上功能)
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: [],
}
如您所见,它返回一个空数组而不是员工的分支ID。我做错了什么?
编辑:
>>> $emp->branch
=> null
答案 0 :(得分:2)
您必须指定外键:
class Employee extends Authenticatable
{
public function branch(){
return $this->belongsTo('App\Branch', 'branch_id');
}
}
并使用$emp->branch
代替$emp->branch()->get()
。
答案 1 :(得分:0)
更改belongsTo()
关系
public function branch(){
return $this->belongsTo('App\Branch', 'branch_id', 'branch_id');
}
答案 2 :(得分:0)
以Jonas的观点为基础,为未来的观众提供更多清晰度:
定义belongsTo关系的实际签名是
return $this->belongsTo('App\Branch', 'branch_id', 'branch_id');
目前,在您使用belongsTo时,您只是定义了与之定义关系的相关实体。您需要做的是提供所有者密钥(而不是外键)的详细信息,因此在您的情况下:
_id
为什么会这样?
Laravel确定使用哪个列的默认行为是:
class SnippetSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
title = serializers.CharField(required=False, allow_blank=True, max_length=100)
code = serializers.CharField(style={'base_template': 'textarea.html'})
linenos = serializers.BooleanField(required=False)
language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')
style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')
后缀。即branch_id 鉴于您在迁移中已经修改了Laravel的默认方法,只需命名主键" branch_id"而不只是" id",你需要告诉Laravel如何关联这两个模型。