Reputation: 21
I am a beginner in laravel world and I face some difficulty in querying many to many relationships in laravel
This is my ERD:
The airline field in the database is just temporary, which ideally I want to query from the airline table instead.
Is it possible to query like
$f = Trip::with('airline')->get();
echo $f->airline->first->name;
Trip.php
class Trip extends Model
{
protected $fillable = [
'capacity', 'fee', 'tour_id', 'flight_id', 'depart_time'
];
public function flight()
{
return $this->belongsToMany(Flight::class);
}
public function airline()
{
return $this->hasManyThrough(Airline::class, Flight::class);
}
}
Flight.php
class Flight extends Model
{
protected $fillable = [
'depart_time', 'arrive_time', 'fee', 'airline_id'
];
public function trip()
{
return $this->belongsToMany(Trip::class);
}
public function airline()
{
return $this->belongsTo(Airline::class);
}
}
Airline.php
class Airline extends Model
{
protected $fillable = ['name'];
public function flights()
{
return $this->hasMany(Flight::class);
}
}
Upvotes: 0
Views: 96
Reputation: 21
for anyone that needs answer / solution... I made a silly mistake to put same name (airline) in both function name in Flight.php and the field of Flight.. after i remove the airline property in the database, everything work just fine.
Upvotes: 1