【问题标题】:Getting the Query Builder object behind fetching a relation in Laravel在 Laravel 中获取关系背后的 Query Builder 对象
【发布时间】:2016-12-10 14:59:02
【问题描述】:

我们在用户模型中使用belongsToMany() 建模了自引用关系。用户可以是彼此的代理或卖方 - 所以我们定义 seller()agents()

现在我们使用https://github.com/Nayjest/Grids,它需要对网格进行查询。

例如,我们希望在网格中显示卖家的代理。

目前我们正在为此使用手工查询 - 但我们想从模型中提取逻辑。

所以我们需要的是在获取时执行的查询(作为查询构建器对象)

$seller = Auth::user(); // or any other instance of User
$seller->agents

我们试过了

$query = $seller->newQuery()->where('laravel_reserved_1.id', '=', $seller->id);
return $user->agents()->getRelationQuery($query, $query);

运气不好。

编辑

尝试 $seller->agents()->getQuery() 我们得到

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in order clause is ambiguous
 (SQL: select * from `users` inner join `user_connections` on 
`users`.`id` = `user_connections`.`user_id` 
where `user_connections`.`related_user_id` = 2 and        
`user_connections`.`type` = agent order by `id` asc 
limit 15 offset 0) 

【问题讨论】:

  • 变量$seller是什么?
  • @TheFallen A 用户实例
  • 不就是$user->agents()->getQuery()吗?

标签: php laravel eloquent


【解决方案1】:

原来只是

$user->agents()->getQuery()

我们在网格中有一个“id”列,这会导致稍后在此过程中出现模棱两可的查询。

【讨论】:

    猜你喜欢
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 2016-08-03
    相关资源
    最近更新 更多