简体   繁体   中英

Laravel models, relationships how to make a innjoin query using Eloquent?

Controller code (which isn`t working)

 $employees = Employee::with('department')->get();

Model:department

class Department extends Model
{
...
/**
 * Defining Relationships.
 */
   public function employee()
   {
    return $this->hasMany('GloboDeals\Employee');
   }
}

Model:employee

class Employee extends Model
{
/**
 * Defining Relationships.
 */
....
 public function department()
{
    return $this->belongsTo('GloboDeals\Department','departments_id','id');
}

the external ids have the name of table_id .

I search and search and none of the solutions are working so I guess my code is just blehhh, if anyone could check it out and give me an idea.

Eloquent will assume that each table has a primary key column named id. You may define a $primaryKey property to override this convention. In each of your models add its primary key like so for Department model:

protected $primaryKey = 'department_id';

Eloquent assumes that the foreign key should have a value matching the id (or the custom $primaryKey) column of the parent. In other words, Eloquent will look for the value of the department id column in the department_id column of the employee record. If you would like the relationship to use a value other than id, you may pass a third argument to the belongsTo method specifying your custom key: In your case you are calling department() of your employee model:

return $this->belongsTo('GloboDeals\Department', 'departments_id', 'departments_id');

This means the Employee model will eager load the department details where the relation departments_id of departments table = departments_id of the employees table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM