dongzhao4036 2013-08-16 19:41
浏览 19
已采纳

如何使用eloquent在Laravel 4中运行查询

I have read the documentation but I can't quite figure out how to run the following query in Laravel 4

SELECT
    COUNT(*)
FROM
    acl a,
    routes r
WHERE
    (a.user_id = 1 OR
     a.group_id IN(SELECT group_id FROM user_group_junction WHERE user_id = 1)) AND
     r.route = 'protected' AND
     a.routes_id = r.id;

So how would I run the query in Laravel 4 using eloquent?

Yes each table has a model and relationships are defined

Based on my selected answer the following is what I came up with (And works)

Acls::join('routes','routes.id','=','acl.routes_id')
                ->where('routes.route','=','protected')
                ->Where(function($in_parenthesis) use($user_id){
                    $in_parenthesis->whereIn('acl.group_id',function($where_in) use($user_id){
                            $where_in->select('group_id')
                                ->from('user_group_junction')
                                ->where('user_id','=',$user_id);
                            })
                    ->orWhere('acl.user_id','=',$user_id);
                })
                ->count();
  • 写回答

1条回答 默认 最新

  • dongyanzhui0524 2013-08-17 02:00
    关注

    Methods called on Eloquent models pass through to the Illuminate\Database\Eloquent\Builder class, which itself extends from the Illuminate\Database\Query\Builder class. This means that all the things you can do with the query builder, you can also do with Eloquent models. The exception being that you don't need to define the table.

    So for example if you wanted to perform a join and a where like you've done above, you would just do:

    $query = Acl::join('routes', 'acl.routes_id', '=', 'routes.id')
                 ->where('routes.route', '=', 'protected');
    
    $results = $query->get();
    

    Obviously this isn't your whole query, but you can figure out the rest.

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

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计