在laravel查询中根据1个条件选择参数

qjp7pelc  于 2023-04-07  发布在  其他
关注(0)|答案(1)|浏览(99)

我在mysql的表中有这样的模式:(https://i.stack.imgur.com/lNf9I.png
我在变量$player_id中保存了ID播放器,在这个表中可以是player_1或player_2
根据这个参数,我想检索对手的玩家ID,所以如果player_1 = player_id得到player_2,否则如果player_2 = player_id得到player_1。我已经尝试了foreach,但效果不好,

public function RedirectToPersonal()
    {
        $torneo = Cache::get('torneo');
        //return $torneo;
        $player_id = DB::table('players')
            ->where('FirstName', '=', Auth::user()->firstName)
            ->where('LastName', '=', Auth::user()->lastName)
            ->value('player_id');

        $player_data = DB::table('tabella_' . $torneo)
            ->orderByDesc('CurrentRoundNumber')
            ->where('player_1', '=', $player_id)
            ->orWhere('player_2', '=', $player_id)
            ->get()
            ->toArray();
        //dump($player_data);

        foreach ($player_data as $key => $value) {
            if ($player_data[$key]->player_1 = $player_id) {
                $names[] = $player_data[$key]->player_2;
            } else {
                $names[] = $player_data[$key]->player_1;
            }
        }
        //dump($player_id);
        //dump($names);

        $data = [
            "player_data" => $player_data,
        ];
        return view('user.personal', $data);

我在查询生成器中需要一个if语句。我该怎么做?

ee7vknir

ee7vknir1#

尝试使用union:

$first = DB::table('tabella_' . $torneo)
            ->selectRaw('player_2 as opponent_id')
            ->where('player_1', $player_id);
 
$opponents = DB::table('tabella_' . $torneo)
            ->selectRaw('player_1 as opponent_id')
            ->where('player_2', $player_id);
            ->union($first)
            ->get();

我相信你仍然可以使用你的代码得到正确的结果。但是,在if语句中,你需要使用==来比较值。还有一件事,你可以使用$value-〉player_1来代替:

//...
   if ($value->player_1 == $player_id) {
   //...

相关问题