duanjiong5023 2016-07-04 19:43
浏览 45
已采纳

在Laravel 5.2中统一/加入数据库和Eloquent的模型查询

I have to check if an user is online (in-game), and if he's not then do another checks to perform a sql update.

Actually, I have these two queries.

$isOnline = DB::connection('mssql')->table('USER_STAT')->where('user_id', $userID)->value('ConnectionStat');
$character = Character::where('acc_id', $userID)->where('Name', $characterName)->firstOrFail();

Is there a way I can use union or join in order to save a DB query? I believe this is not a good practice, and some better method is out there, which I can't find in the docs.

I tried something like this, but without success:

$character = Character::where('acc_id', $userID)->where('Name', $characterName)->firstOrFail();
$result = DB::connection('mssql')->table('USER_STAT')->where('user_id', $userID)->union($character)->get();

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • dongzhan5246 2016-07-05 08:39
    关注

    Using a relation in your Character Model to the Model of the USER_STAT table you can easily lookup the things you need to determine if an update somewhere is needed.

    Eloquent Relationships

    This does not consolidate the queries into one, like with a join, but they are not heavy anyway, and using the ORM to the fullest will have more significant advantages in the long run.

    If you think you must use an SQL-join you must stick to the querybuilder, but the ORM is usually the better choice

    Query Builder Joins

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签)
  • ¥50 sft下载大文阻塞卡死
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失
  • ¥15 springboot+vue 集成keycloak sso到阿里云
  • ¥15 win7系统进入桌面过一秒后突然黑屏
  • ¥30 backtrader对于期货交易的现金和资产计算的问题
  • ¥15 求C# .net4.8小报表工具
  • ¥15 安装虚拟机时出现问题