In my case, I have three tables:
type
id
type
reason
id
reason
permission
- id
One type has many reasons
Reason belong To type
Permission has many type , each type has many reasons
{
"message": "Get each permission with type and reason",
"data": [
{
"id": "1",
"types": [
"id": "1",
"type": "Sick",
"reasons": [
"id": "1",
"reason": "covid-19"
]
]
}
Please help add foreignkey to model .
CodePudding user response:
each permission with type and reason in Laravel, you need to create models for each table and define the relationships between them.
// Type model
class Type extends Model
{
public function reasons()
{
return $this->hasMany('App\Reason');
}
public function permissions()
{
return $this->belongsToMany('App\Permission');
}
}
// Reason model
class Reason extends Model
{
public function type()
{
return $this->belongsTo('App\Type');
}
public function permissions()
{
return $this->belongsToMany('App\Permission');
}
}
// Permission model
class Permission extends Model
{
public function types()
{
return $this->belongsToMany('App\Type');
}public function reasons()
{
return $this->belongsToMany('App\Reason');
}
}
each permission with type and reason, you can use the following code:
$permissions = Permission::with('types', 'types.reasons')->get();
return response()->json(['message' => 'Get each permission with type and reason', 'data' => $permissions], 200);
Note: You need to create pivot tables for the many-to-many relationships between Permission and Type and between Permission and Reason.