I'm new to Laravel. I have a problem on laravel relationship. Can you guys help me?
I have four tables:
1. Users
2. Teams
3. Games
4. Picks
Picks is my intermediate table model
1. id
2. user_id
3. team_id
4. game_id
User class
class User extends Model
{
public function picks()
{
return $this->hasMany('App\Models\Pick');
}
}
Team class
class Team extends Model
{
public function picks()
{
return $this->hasMany('App\Models\Pick');
}
}
Game class
class Game extends Model
{
public function picks()
{
return $this->hasMany('App\Models\Pick');
}
}
class Pick extends Model
{
public function users()
{
return $this->belongsToMany('App\Models\User');
}
public function teams()
{
return $this->belongsToMany('App\Models\Team');
}
public function schedules()
{
return $this->belongsToMany('App\Models\Schedule');
}
}
How can I convert this query to eloquent?
"SELECT * FROM `games` AS g LEFT JOIN `picks` as p ON p.game_id = g.id LEFT JOIN `users` as u ON u.id = p.user_id WHERE u.id = 1;"
I want to get games through the picks via user id.
You are trying to jump over the table. Check the documentation:
https://laravel.com/docs/5.8/eloquent-relationships#has-many-through
you almost got it right tho.
Your User model relation should match the class what is trying to reach, the table between al handled in the background.
class User extends Model
{
public function games()
{
return $this->belongsToMany(Games::class, 'picks'); <-- i prefer this over string
}
}
then somewhere in your controller you can just do this
$user = User::find(1);
$games = $user->games; <-- should work but if not
$games = $user->games()->get() <-- has to do with lazy loading.
EDIT: i changed the table to picks at the relationship
Your Pick
model is wrong. All the relationships should be BelongsTo()
instead of BelongsToMany()
since a Pick belongs to only one User one Team and one Schedule.
Pick Model
class Pick extends Model
{
public function user()
{
return $this->belongsTo('App\Models\User');
}
public function team()
{
return $this->belongsTo('App\Models\Team');
}
public function schedule()
{
return $this->belongsTo('App\Models\Schedule');
}
}
Now, to get Games for particular Pick Which belongs to a Particular User.
Controller Function
$userId = '1';
$games = Game::whereHas('picks', function($query) use ($userId) {
// Here you have a query for picks table.
$query->where('user_id', $userId);
})
->get();
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.