我一直在寻找,但还没有找到解决方案。
在我的laravel项目中,我有一个名为players
的表。每位玩家都有position_id
和team_id
。使用关系。
以下是我的模特:
use Illuminate\Database\Eloquent\Model;
class Team extends Model
{
public function players()
{
return $this->hasMany('App\Player');
}
}
use Illuminate\Database\Eloquent\Model;
class Position extends Model
{
public function players()
{
return $this->hasMany('App\Player');
}
}
use Illuminate\Database\Eloquent\Model;
class Player extends Model
{
public function team()
{
return $this->belongsTo('App\Team');
}
public function position()
{
return $this->belongsTo('App\Position');
}
}
如果我希望所有position==gk
玩家都参加:
$players = Position::whereDescription('gk')->players;
如果我想让team==pac
的所有玩家都参与:
$players = Team::whereDescription('pac')->players;
如何查询来自team==pac
position==gk
的所有玩家?
答案 0 :(得分:0)
试试这个:
Player::where(['position_id'=>$positionId, 'team_id'=>$teamId])->first();
或
Player::where(['position_id'=>$positionId, 'team_id'=>$teamId])->get();
但是,此代码并未充分利用Eloquent关系,并假设您已经拥有$postionId
和$teamId
。