如何查询属于表的两个具有两种不同关系的外键

时间:2015-07-19 02:36:54

标签: eloquent laravel-5

我一直在寻找,但还没有找到解决方案。

在我的laravel项目中,我有一个名为players的表。每位玩家都有position_idteam_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的所有玩家?

1 个答案:

答案 0 :(得分:0)

试试这个:

Player::where(['position_id'=>$positionId, 'team_id'=>$teamId])->first();

Player::where(['position_id'=>$positionId, 'team_id'=>$teamId])->get();

但是,此代码并未充分利用Eloquent关系,并假设您已经拥有$postionId$teamId