I want to retrieve the users risk categories
risks table
id
risk
category_id
risk_user table
id
risk_id
user_id
risk_categorys
id
category
To retrieve a risks category works fine, in my model I do this:
class Risk extends Eloquent{
protected $table = 'risks';
public $timestamps = false;
public function users()
{
return $this->belongsToMany('User');
}
public function category()
{
return $this->belongsTo('RiskCategory');
}
}
But I struggle when it comes to retrieving all of the risk categories for a specific user.
I'd do it this way:
User Model
class User extends Eloquent{
public function risks(){
return $this->belongsToMany('Risk');
}
}
Then you can use Eager Loading to get the category for all your risks.
Query
User::find(1)->risks()->with('category')->get();
Since I don't have all your code nor your database I can't test it, but theoretically it should work ;) if not, just leave me a comment.
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.