【问题标题】:Query relationship Eloquent查询关系 Eloquent
【发布时间】:2013-11-30 22:09:40
【问题描述】:

我有News 模型,而News 有很多cmets,所以我在News 模型中做了这个:

public function comments(){
    $this->hasMany('Comment', 'news_id');
}

但我在comments 表中也有字段trashed,我只想选择未被丢弃的cmets。所以trashed <> 1。所以我想知道有没有办法做这样的事情:

$news = News::find(123);
$news->comments->where('trashed', '<>', 1); //some sort of pseudo-code

有没有办法使用上面的方法或者我应该写这样的东西:

$comments = Comment::where('trashed', '<>', 1)
    ->where('news_id', '=', $news->id)
    ->get();

【问题讨论】:

    标签: php laravel laravel-4 eloquent


    【解决方案1】:

    其中任何一个都应该适合你,选择你最喜欢的一个:

    1. 渴望加载。

      $comments = News::find(123)->with(['comments' => function ($query) {
          $query->where('trashed', '<>', 1);
      }])->get();
      

      您可以通过use($param) 方法将参数注入到查询函数中,这样您就可以在运行时使用动态查询值。

    2. 延迟加载

      $news = News::find(123);
      $comments = $news->comments()->where('trashed', '<>', 1)->get();
      

    不过,我不禁注意到,您可能正在尝试做的是处理软删除,而 Laravel 有内置功能可以帮助您:http://laravel.com/docs/eloquent#soft-deleting

    【讨论】:

    • 我已经实现了软删除,但我也希望 cmets 未发布但未删除。我也有删除选项
    【解决方案2】:

    rmobis 的答案是我所需要的,但它在当前的 Laravel 5 中引发了错误。您现在必须将它用作关联数组:

    $comments = News::find(123)->with(
        ['comments' => function ($query) {$query->where('trashed', '<>', 1);}]
    );
    

    我花了一些时间弄清楚,希望这对其他人有帮助。

    在 Laravel 的文档 (5.6) 中阅读更多内容:https://laravel.com/docs/5.6/eloquent-relationships#querying-relations

    【讨论】:

      【解决方案3】:

      您可以简单地在您的 eloquent 模型文件中进行操作。 这样做:

      public function comments_with_deleted()
      {
          return $this->belongsTo('Comments', 'id')->where('deleted', 1);
      }
      
      public function comments()
      {
          return $this->belongsTo('Comments', 'id');
      }
      

      这样调用:

      // for show comments with deleted
      $comments = News::find(123)->with('comments_with_deleted');
      
      // for show comments without deleted
      $comments = News::find(123)->with('comments');
      

      【讨论】:

        猜你喜欢
        • 2021-06-10
        • 2013-10-03
        • 2017-07-19
        • 1970-01-01
        • 1970-01-01
        • 2021-09-25
        • 2015-01-21
        • 2017-11-14
        • 2017-01-14
        相关资源
        最近更新 更多