So we would have two tables in our DB represented by two models: Events and Games. In the 'events' table the colmuns would be: id, name, start_date, ... And in the 'games' table the columns would be: id, name, event_id, ... Where event_id is an foreign key to the column id in events.
And for the Laravel models:
class Event extends Eloquent {
protected $table = 'events';
public function games()
{
return $this->hasMany('Games');
}
}
class Games extends Eloquent {}
So now, to retrieve all the games of the events with id 1, you only have to do this:
$games = Event::find(1)->games;
Can you explain to me why a relationship isn't made in the games model?
Saluki said:
So we would have two tables in our DB represented by two models: Events and Games. In the 'events' table the colmuns would be: id, name, start_date, ... And in the 'games' table the columns would be: id, name, event_id, ... Where event_id is an foreign key to the column id in events.
And for the Laravel models:
class Event extends Eloquent { protected $table = 'events'; public function games() { return $this->hasMany('Games'); } } class Games extends Eloquent {}
So now, to retrieve all the games of the events with id 1, you only have to do this:
$games = Event::find(1)->games;
The relation that there is between your 'events' table and 'games' table is one-to-many. This means that an event can have multiple games but games could only refer to an event...
When I have that sort of relation, I use it to fetch all the sub-rows (games) of the main-row (event). For example, fetch all the games for the event with ID 23.
But you're right... we can complete the model to retrieve the event of a game. For example: what's the event for the game with ID 145? You only have to add the following the function in your Games model:
class Games extends Eloquent {
public function event()
{
return $this->belongsTo('Event');
}
}
Great explanation. Well done.
Saluki said:
The relation that there is between your 'events' table and 'games' table is one-to-many. This means that an event can have multiple games but games could only refer to an event...
When I have that sort of relation, I use it to fetch all the sub-rows (games) of the main-row (event). For example, fetch all the games for the event with ID 23.
But you're right... we can complete the model to retrieve the event of a game. For example: what's the event for the game with ID 145? You only have to add the following the function in your Games model:
class Games extends Eloquent { public function event() { return $this->belongsTo('Event'); } }
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community