【问题标题】:Laravel Eloquent using an alias with the with() functionLaravel Eloquent 使用带有 with() 函数的别名
【发布时间】:2018-02-27 21:31:38
【问题描述】:

美好的一天。在 laravel 中使用 with() 函数时是否可以使用别名?举个例子:

$posts = Post::where(/*condition*/)->with('user as friend')->get();

【问题讨论】:

  • 一个帖子可以有很多朋友还是只有一个?
  • $post->user$post->friend 是两个不同的结果。但我已经创建了一个检查if ($post->friend->id == ?) 的函数,我试图避免与它重复:if ($post->user->id == ?)
  • 我不确定我是否理解,您已经为friend 定义了关系,但结果与user 不同?

标签: php laravel eloquent


【解决方案1】:

简短的回答是否定的,但您可以定义与要使用的别名的关系并立即加载。

class Post extends Model
    public function user(){
        return $this->belongsTo(User::class);
    }

    public function friend(){
        return $this->user()
    }
}

$posts = Post::where(/*condition*/)->with('friend')->get();

【讨论】:

  • $post->user$post->friend 是两个不同的结果。但我已经创建了一个检查if ($post->friend->id == ?) 的函数,我试图避免像这样重复它:if ($post->user->id == ?)
  • 出于某种原因,有人赞成我的回答。我忘了跟进这件事。 @LukhoMdingi 是否需要更新?
  • 我从来没有真正找到解决方案。我不得不解决它。
猜你喜欢
  • 1970-01-01
  • 2015-06-13
  • 2020-04-26
  • 1970-01-01
  • 2013-11-20
  • 1970-01-01
  • 2017-04-01
  • 2013-05-27
相关资源
最近更新 更多