Previously I have worked with bog standard PHP and have recently made the move over to Laravel. One thing I cannot grasp is SQL queries in Laravel Eloquent.
For instance I have a roles and a users table. The roles table contains roles and IDs for each role. The users table contains various user details as well as a role_id to reference the role of the user.
What I have tried in my user model
public function role()
{
// return $this->hasOne('App\Phone', 'foreign_key', 'local_key');
return $this->hasOne('App\Role', 'id', 'role_id');
}
What I have tried in my role model
public function users()
{
return $this->hasMany('App\User', 'role_id', 'id');
}
Then in my controller
public function index()
{
$var = User::find()->role->get();
return view('article',
array(
'var' => $var
));
}
But now how do I access the fields in both tables as I would in ordinary PHP? I would rather use standard SQL but am trying to properly learn this framework.
Any advice?
hasOne('App\Role', 'role_id', 'id');
, but in fact you can just ommit the keys and eloquent will guess them right in your case. – Jarek TkaczykbelongsTo('App\Role')
for therole()
relation. This is how a 1-to-many relationship is modelled on the many side. – Jared Rolt