Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel 连接查询中有说服力的代码重复_Laravel_Eloquent - Fatal编程技术网

Laravel 连接查询中有说服力的代码重复

Laravel 连接查询中有说服力的代码重复,laravel,eloquent,Laravel,Eloquent,是否有适合laravel/Elount处理以下代码重复的设计模式: 用户有相册,相册有照片,照片有标签 我有一个特殊的查询来加入来自单个相册和标签的照片 public function GetJoinedAlbum() { return Photos::where(...in a specific album ...)-> join(... tags ...)-> ... } 我使用相同的连接查询来连接带有标记的用户的所有照片 Photos::where(..

是否有适合laravel/Elount处理以下代码重复的设计模式:

用户有相册,相册有照片,照片有标签

我有一个特殊的查询来加入来自单个相册和标签的照片

public function GetJoinedAlbum()
{
    return Photos::where(...in a specific album ...)->
       join(... tags ...)-> ...
}
我使用相同的连接查询来连接带有标记的用户的所有照片

Photos::where(... belong to a specific user ...)
        join(... tags ...)->...
我无法使用“with”,因为我想继续查询结果

GetJoinedAlbum()->where('........')
急装

尽量使用急切的住宿

$user->with('album.photos.tags');
原始查询

然后,从查询中可以获得绑定、位置和联接

   $joins = $yourBaseQuery->joins;
   $wheres = $yourBaseQuery->wheres;
   $bindings = $yourBaseQuery->getBindings();
   $anotherQuery = $query->join(...)->join(...)->where(...)->getQuery();
   $anotherQuery->joins = array_merge($joins, $anotherQuery->joins);
   $anotherQuery->mergeWheres($wheres, $bindings);
   $result = $anotherQuery->first(); // or all, or continure build your query.

因此,您的另一个查询将具有连接,其中来自第一个查询的连接和绑定

是的,您可以使用Laravel Earge loading获得所有结果

获取用户所有相册,然后是所有相册照片,然后是照片标签

User::with(['albums.photos.tags'])->where('username',$user)->firstOrFail();
您甚至可以查询嵌套关系,如

return User::with(['albums' => function($query){
            $query->where('id',1);
        }])->where('username',$user)->firstOrFail();

请参阅有关我无法与一起使用的

的详细信息,因为我希望继续从函数范围之外查询结果。请参阅更新的问题。您还可以进一步查询。请看上面的例子,我正在使用渴望加载,但我也在进一步查询用户模型,通过用户名获取用户,在第二个例子中,我在查询关系,您也可以将变量传递给这个匿名函数,如函数$query use$anyvariable{}是的,我看到了,但我无法将查询链接到联接表。User::with'albums'->where'id',1和我希望函数返回一个可查询的对象。如果我加入,那么我将能够链接任何查询。您可以并且应该使用with。你只需要知道你想在哪张表上设置什么约束——读一下这个,因为你需要知道的就是这些
return User::with(['albums' => function($query){
            $query->where('id',1);
        }])->where('username',$user)->firstOrFail();