Reputation: 773
This is a section of Two of my related models in 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');
}
}
And these are the migrations of the above two models (up function only)
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');
});
}
When I run php artisan tinker
and test out the relationship, I get the following output:
>>> 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: [],
}
As you can see, it returns an empty array instead of the branch id of the employee. What have I done wrong?
EDIT:
>>> $emp->branch
=> null
Upvotes: 1
Views: 1447
Reputation: 21
To build on Jonas's point, and to provide more clarity for future viewers:
The actual signature for defining a belongsTo relationship is
belongsTo(relatedEntity, foreignKey, ownerKey, relationModel)
At present, in your use of belongsTo, you're only defining which related entity you are defining a relationship with. What you need to do is provide details of the owner key (rather than the foreign key), so in your case:
return $this->belongsTo('App\Branch', 'branch_id', 'branch_id');
Why is this the case?
Laravel's default behaviour for determining which column to utilise is:
_id
suffix. I.e. branch_idGiven that in your migrations you've modified Laravel's default approach, by naming your primary key "branch_id" rather than just "id", you need to tell Laravel how to relate the two models.
Upvotes: 0
Reputation: 9853
Change your belongsTo()
relationship
public function branch(){
return $this->belongsTo('App\Branch', 'branch_id', 'branch_id');
}
Upvotes: 0
Reputation: 25906
You have to specify the foreign key:
class Employee extends Authenticatable
{
public function branch(){
return $this->belongsTo('App\Branch', 'branch_id');
}
}
And use $emp->branch
instead of $emp->branch()->get()
.
Upvotes: 2