Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/245.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.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
Php 使用with Eloquent方法添加表别名检索关系_Php_Laravel_Eloquent - Fatal编程技术网

Php 使用with Eloquent方法添加表别名检索关系

Php 使用with Eloquent方法添加表别名检索关系,php,laravel,eloquent,Php,Laravel,Eloquent,我知道当您使用with方法和elount检索关系时,是否可以为表提供别名 例如: Post::where('title', 'like', '%' . $title . '%') ->where('published', 1) ->with(['medias AS jpeg' => function($q) { $q->where('format', 'jpeg'); }])->with(['medias AS gif' =&

我知道当您使用
with
方法和elount检索关系时,是否可以为表提供别名

例如:

Post::where('title', 'like', '%' . $title . '%')
    ->where('published', 1)
    ->with(['medias AS jpeg' => function($q) {
          $q->where('format', 'jpeg'); 
 }])->with(['medias AS gif' => function($q) {
          $q->where('format', 'gif');
 }])->first();
我知道这不管用,但这是为了给你一个机会

是否有可能或必须手动执行此操作


提前谢谢。

这是不可能的,因为
with
不接受表,而接受关系名称,并且只存储给定关系的结果一次

因此,只需定义不同的关系:

public function gifs()
{
  return $this->hasMany('Media')->where('format', 'gif');
}

public function jpegs()
{
  return $this->hasMany('Media')->where('format', 'jpeg');
}

有很多
或任何明显的关系类型。

谢谢你的回答,很简单。但另一个问题,例如,我有三个表,分别是international\u content\u fr、international\u content\u en和international\u content\u cn,所以我有三个关系方法,所以当我加载时,我可以将一个参数传递给关系方法,以便每个国际表只有一个关系方法。不,您不能将任何参数传递给渴望加载的方法。检查这种情况下的多态关系。事实上,我可以通过测试值是否为闭包来修改laravel中的Builder类中的方法,如果不是,则将值作为参数传递,这更简单,但您的解决方案更干净。是的,您可以随时调整泛型类,但这不是最好的方法,甚至不好;)