dongmaopiao0901 2019-02-05 19:28
浏览 45

Laravel Eloquent - 使用关系将查询与单一查询相结合

I'm working on a project where I'm using Laravel Eloquent to fetch all my data from my database.

I'm storing basketball clubs, teams and players in different tables. Now I want to select all basketball players that belong to a team that belongs to a club.

I created a relation in the Club model:

public function basketballPlayers()
    {
        return $this->hasManyThrough('App\Models\Basketball\BasketballPlayer','App\Models\Basketball\BasketballTeam','id','team_id');
    }

And a user relation in the BasketballPlayer model:

public function user()
    {
        return $this->hasOne('App\User','id','user_id');
    }

Now when I execute the following command, DB::getQueryLog() returns 3 Queries.

Club::findOrFail($club_id)->basketballPlayers()->with('user')->get();

But when I execute the following command without using relations, DB::getQueryLog() returns only 1 query.

$players = BasketballPlayer::Join('basketball_teams','basketball_teams.id','=','basketball_players.team_id')
            ->join('users','users.id','=','basketball_players.user_id')
            ->where('basketball_teams.club_id','=',$authUser->club_id)
            ->get(['basketball_players.*','users.firstname','users.lastname','basketball_teams.name']);

I don't need all the data from the club and the user (see ->get(...) in the Join query).

Is it possible to achieve the same result like in the "long" manual Join-query using the much cleaner and simpler Eloquent relation approach?

Thanks for your help!

  • 写回答

1条回答 默认 最新

  • dongren5293 2019-02-05 19:34
    关注

    You can read less data using with (not all user columns as example) by this

    Club::findOrFail($club_id)
        ->basketballPlayers()
        ->with('user:id,firstname,lastname')   // <- here is change
        ->get();
    

    The id (and foreign keys) column is important. You should be also able to make nested with in following way (I write code from head - so please test it):

    Club::findOrFail($club_id)
        ->with('BasketballPlayer:id,user_id')
        ->with('BasketballPlayer.user:id,firstname,lastname')   
        ->get();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作