Laravel : Get all models that their last relationship have some condition












3















I have two models Post and Comment, i'd like to get all posts that their last comment is active:



// Model Post
public function comments()
{
return $this->hasMany('comments');
}

//Model Comment
public function post()
{
return $this->belongsTo('post');
}


i tried this solution :



public function lastComment()
{
return $this->hasOne('comment')->latest()
}


and in my controller :



$postsWithLastActiveComment = Post::whereHas('lastComment', function($q){
$q->where('active',1);
})->all();


but in this solution if the last comment is not active Previous comment will be taken










share|improve this question

























  • See stackoverflow.com/a/50687657/4848587.

    – Jonas Staudenmeir
    Jan 20 at 13:59
















3















I have two models Post and Comment, i'd like to get all posts that their last comment is active:



// Model Post
public function comments()
{
return $this->hasMany('comments');
}

//Model Comment
public function post()
{
return $this->belongsTo('post');
}


i tried this solution :



public function lastComment()
{
return $this->hasOne('comment')->latest()
}


and in my controller :



$postsWithLastActiveComment = Post::whereHas('lastComment', function($q){
$q->where('active',1);
})->all();


but in this solution if the last comment is not active Previous comment will be taken










share|improve this question

























  • See stackoverflow.com/a/50687657/4848587.

    – Jonas Staudenmeir
    Jan 20 at 13:59














3












3








3


2






I have two models Post and Comment, i'd like to get all posts that their last comment is active:



// Model Post
public function comments()
{
return $this->hasMany('comments');
}

//Model Comment
public function post()
{
return $this->belongsTo('post');
}


i tried this solution :



public function lastComment()
{
return $this->hasOne('comment')->latest()
}


and in my controller :



$postsWithLastActiveComment = Post::whereHas('lastComment', function($q){
$q->where('active',1);
})->all();


but in this solution if the last comment is not active Previous comment will be taken










share|improve this question
















I have two models Post and Comment, i'd like to get all posts that their last comment is active:



// Model Post
public function comments()
{
return $this->hasMany('comments');
}

//Model Comment
public function post()
{
return $this->belongsTo('post');
}


i tried this solution :



public function lastComment()
{
return $this->hasOne('comment')->latest()
}


and in my controller :



$postsWithLastActiveComment = Post::whereHas('lastComment', function($q){
$q->where('active',1);
})->all();


but in this solution if the last comment is not active Previous comment will be taken







laravel laravel-5 eloquent






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 20 at 7:57







Joseph Rback

















asked Jan 20 at 7:20









Joseph RbackJoseph Rback

202313




202313













  • See stackoverflow.com/a/50687657/4848587.

    – Jonas Staudenmeir
    Jan 20 at 13:59



















  • See stackoverflow.com/a/50687657/4848587.

    – Jonas Staudenmeir
    Jan 20 at 13:59

















See stackoverflow.com/a/50687657/4848587.

– Jonas Staudenmeir
Jan 20 at 13:59





See stackoverflow.com/a/50687657/4848587.

– Jonas Staudenmeir
Jan 20 at 13:59












5 Answers
5






active

oldest

votes


















1














->latest() only orders the posts by created_at so to get only the latest comment you need ->latest()->first()






share|improve this answer
























  • Call to undefined method IlluminateDatabaseQueryBuilder::getRelated()

    – Joseph Rback
    Jan 20 at 7:31











  • first method is not allowed in relationship query

    – Joseph Rback
    Jan 20 at 7:34











  • You're getting getRelated error because your Comments relation is a HasMany, not as HasOne (even though you only want one). So you can put: $this->hasMany('comments')->latest()->first()

    – Matt Wohler
    Jan 20 at 7:36











  • i got same error with hasMany

    – Joseph Rback
    Jan 20 at 7:41



















1














I think the code below should work !



public function comments()
{
return $this->hasMany('comments');
}

public function lastComment()
{
return $this->comments()->latest()->first();
}





share|improve this answer































    1














    Shouldn't this



    $postsWithLastActiveComment = Post::whereHas('lastComment', function($q){
    $q->where('active',1);
    })->all();


    be



     $postsWithLastActiveComment = Post::whereHas('lastComment', function($q){
    $q->where('active',1);
    })->get();





    share|improve this answer































      1














      I am not sure if there's another simpler way of doing this, but maybe you can try it with a sub-query?



      $lastComment = Comment::select('active')
      ->whereColumn('post_id', 'posts.id')
      ->latest()
      ->limit(1)
      ->getQuery();

      $posts = Post::select('posts.*')
      ->selectSub($lastComment, 'last_comment_is_active')
      ->having('last_comment_is_active', 1)
      ->get();





      share|improve this answer

































        0














        According to your question, the Post model has many Comments. And you want to get the comment from the post where active is one and must be the lastest id.



        Get the last comment like the following



        public function lastComment()
        {
        return $this->hasOne('comment')->latest()->take(1);
        }


        Get all posts which had the lastComment like the following



        $latestCommentPosts = Post::whereHas('lastComment')->get()


        And filter the latestCommentPosts like the following



        $latestCommentPosts->where('active', 1)->get()


        Or, you can archive by one query like the following as well.



        Post::whereHas('comments', function($q) { 
        $q->where('active', 1);
        })->get()


        Like that, you got all the latest comment with active is 1.






        share|improve this answer

























          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54274389%2flaravel-get-all-models-that-their-last-relationship-have-some-condition%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          5 Answers
          5






          active

          oldest

          votes








          5 Answers
          5






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          ->latest() only orders the posts by created_at so to get only the latest comment you need ->latest()->first()






          share|improve this answer
























          • Call to undefined method IlluminateDatabaseQueryBuilder::getRelated()

            – Joseph Rback
            Jan 20 at 7:31











          • first method is not allowed in relationship query

            – Joseph Rback
            Jan 20 at 7:34











          • You're getting getRelated error because your Comments relation is a HasMany, not as HasOne (even though you only want one). So you can put: $this->hasMany('comments')->latest()->first()

            – Matt Wohler
            Jan 20 at 7:36











          • i got same error with hasMany

            – Joseph Rback
            Jan 20 at 7:41
















          1














          ->latest() only orders the posts by created_at so to get only the latest comment you need ->latest()->first()






          share|improve this answer
























          • Call to undefined method IlluminateDatabaseQueryBuilder::getRelated()

            – Joseph Rback
            Jan 20 at 7:31











          • first method is not allowed in relationship query

            – Joseph Rback
            Jan 20 at 7:34











          • You're getting getRelated error because your Comments relation is a HasMany, not as HasOne (even though you only want one). So you can put: $this->hasMany('comments')->latest()->first()

            – Matt Wohler
            Jan 20 at 7:36











          • i got same error with hasMany

            – Joseph Rback
            Jan 20 at 7:41














          1












          1








          1







          ->latest() only orders the posts by created_at so to get only the latest comment you need ->latest()->first()






          share|improve this answer













          ->latest() only orders the posts by created_at so to get only the latest comment you need ->latest()->first()







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 20 at 7:26









          JoshJosh

          729213




          729213













          • Call to undefined method IlluminateDatabaseQueryBuilder::getRelated()

            – Joseph Rback
            Jan 20 at 7:31











          • first method is not allowed in relationship query

            – Joseph Rback
            Jan 20 at 7:34











          • You're getting getRelated error because your Comments relation is a HasMany, not as HasOne (even though you only want one). So you can put: $this->hasMany('comments')->latest()->first()

            – Matt Wohler
            Jan 20 at 7:36











          • i got same error with hasMany

            – Joseph Rback
            Jan 20 at 7:41



















          • Call to undefined method IlluminateDatabaseQueryBuilder::getRelated()

            – Joseph Rback
            Jan 20 at 7:31











          • first method is not allowed in relationship query

            – Joseph Rback
            Jan 20 at 7:34











          • You're getting getRelated error because your Comments relation is a HasMany, not as HasOne (even though you only want one). So you can put: $this->hasMany('comments')->latest()->first()

            – Matt Wohler
            Jan 20 at 7:36











          • i got same error with hasMany

            – Joseph Rback
            Jan 20 at 7:41

















          Call to undefined method IlluminateDatabaseQueryBuilder::getRelated()

          – Joseph Rback
          Jan 20 at 7:31





          Call to undefined method IlluminateDatabaseQueryBuilder::getRelated()

          – Joseph Rback
          Jan 20 at 7:31













          first method is not allowed in relationship query

          – Joseph Rback
          Jan 20 at 7:34





          first method is not allowed in relationship query

          – Joseph Rback
          Jan 20 at 7:34













          You're getting getRelated error because your Comments relation is a HasMany, not as HasOne (even though you only want one). So you can put: $this->hasMany('comments')->latest()->first()

          – Matt Wohler
          Jan 20 at 7:36





          You're getting getRelated error because your Comments relation is a HasMany, not as HasOne (even though you only want one). So you can put: $this->hasMany('comments')->latest()->first()

          – Matt Wohler
          Jan 20 at 7:36













          i got same error with hasMany

          – Joseph Rback
          Jan 20 at 7:41





          i got same error with hasMany

          – Joseph Rback
          Jan 20 at 7:41













          1














          I think the code below should work !



          public function comments()
          {
          return $this->hasMany('comments');
          }

          public function lastComment()
          {
          return $this->comments()->latest()->first();
          }





          share|improve this answer




























            1














            I think the code below should work !



            public function comments()
            {
            return $this->hasMany('comments');
            }

            public function lastComment()
            {
            return $this->comments()->latest()->first();
            }





            share|improve this answer


























              1












              1








              1







              I think the code below should work !



              public function comments()
              {
              return $this->hasMany('comments');
              }

              public function lastComment()
              {
              return $this->comments()->latest()->first();
              }





              share|improve this answer













              I think the code below should work !



              public function comments()
              {
              return $this->hasMany('comments');
              }

              public function lastComment()
              {
              return $this->comments()->latest()->first();
              }






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Jan 20 at 8:42









              GomsGoms

              654721




              654721























                  1














                  Shouldn't this



                  $postsWithLastActiveComment = Post::whereHas('lastComment', function($q){
                  $q->where('active',1);
                  })->all();


                  be



                   $postsWithLastActiveComment = Post::whereHas('lastComment', function($q){
                  $q->where('active',1);
                  })->get();





                  share|improve this answer




























                    1














                    Shouldn't this



                    $postsWithLastActiveComment = Post::whereHas('lastComment', function($q){
                    $q->where('active',1);
                    })->all();


                    be



                     $postsWithLastActiveComment = Post::whereHas('lastComment', function($q){
                    $q->where('active',1);
                    })->get();





                    share|improve this answer


























                      1












                      1








                      1







                      Shouldn't this



                      $postsWithLastActiveComment = Post::whereHas('lastComment', function($q){
                      $q->where('active',1);
                      })->all();


                      be



                       $postsWithLastActiveComment = Post::whereHas('lastComment', function($q){
                      $q->where('active',1);
                      })->get();





                      share|improve this answer













                      Shouldn't this



                      $postsWithLastActiveComment = Post::whereHas('lastComment', function($q){
                      $q->where('active',1);
                      })->all();


                      be



                       $postsWithLastActiveComment = Post::whereHas('lastComment', function($q){
                      $q->where('active',1);
                      })->get();






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Jan 20 at 9:00









                      Iftikhar uddinIftikhar uddin

                      1,33911223




                      1,33911223























                          1














                          I am not sure if there's another simpler way of doing this, but maybe you can try it with a sub-query?



                          $lastComment = Comment::select('active')
                          ->whereColumn('post_id', 'posts.id')
                          ->latest()
                          ->limit(1)
                          ->getQuery();

                          $posts = Post::select('posts.*')
                          ->selectSub($lastComment, 'last_comment_is_active')
                          ->having('last_comment_is_active', 1)
                          ->get();





                          share|improve this answer






























                            1














                            I am not sure if there's another simpler way of doing this, but maybe you can try it with a sub-query?



                            $lastComment = Comment::select('active')
                            ->whereColumn('post_id', 'posts.id')
                            ->latest()
                            ->limit(1)
                            ->getQuery();

                            $posts = Post::select('posts.*')
                            ->selectSub($lastComment, 'last_comment_is_active')
                            ->having('last_comment_is_active', 1)
                            ->get();





                            share|improve this answer




























                              1












                              1








                              1







                              I am not sure if there's another simpler way of doing this, but maybe you can try it with a sub-query?



                              $lastComment = Comment::select('active')
                              ->whereColumn('post_id', 'posts.id')
                              ->latest()
                              ->limit(1)
                              ->getQuery();

                              $posts = Post::select('posts.*')
                              ->selectSub($lastComment, 'last_comment_is_active')
                              ->having('last_comment_is_active', 1)
                              ->get();





                              share|improve this answer















                              I am not sure if there's another simpler way of doing this, but maybe you can try it with a sub-query?



                              $lastComment = Comment::select('active')
                              ->whereColumn('post_id', 'posts.id')
                              ->latest()
                              ->limit(1)
                              ->getQuery();

                              $posts = Post::select('posts.*')
                              ->selectSub($lastComment, 'last_comment_is_active')
                              ->having('last_comment_is_active', 1)
                              ->get();






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Jan 20 at 9:06

























                              answered Jan 20 at 8:48









                              MozammilMozammil

                              6,085419




                              6,085419























                                  0














                                  According to your question, the Post model has many Comments. And you want to get the comment from the post where active is one and must be the lastest id.



                                  Get the last comment like the following



                                  public function lastComment()
                                  {
                                  return $this->hasOne('comment')->latest()->take(1);
                                  }


                                  Get all posts which had the lastComment like the following



                                  $latestCommentPosts = Post::whereHas('lastComment')->get()


                                  And filter the latestCommentPosts like the following



                                  $latestCommentPosts->where('active', 1)->get()


                                  Or, you can archive by one query like the following as well.



                                  Post::whereHas('comments', function($q) { 
                                  $q->where('active', 1);
                                  })->get()


                                  Like that, you got all the latest comment with active is 1.






                                  share|improve this answer






























                                    0














                                    According to your question, the Post model has many Comments. And you want to get the comment from the post where active is one and must be the lastest id.



                                    Get the last comment like the following



                                    public function lastComment()
                                    {
                                    return $this->hasOne('comment')->latest()->take(1);
                                    }


                                    Get all posts which had the lastComment like the following



                                    $latestCommentPosts = Post::whereHas('lastComment')->get()


                                    And filter the latestCommentPosts like the following



                                    $latestCommentPosts->where('active', 1)->get()


                                    Or, you can archive by one query like the following as well.



                                    Post::whereHas('comments', function($q) { 
                                    $q->where('active', 1);
                                    })->get()


                                    Like that, you got all the latest comment with active is 1.






                                    share|improve this answer




























                                      0












                                      0








                                      0







                                      According to your question, the Post model has many Comments. And you want to get the comment from the post where active is one and must be the lastest id.



                                      Get the last comment like the following



                                      public function lastComment()
                                      {
                                      return $this->hasOne('comment')->latest()->take(1);
                                      }


                                      Get all posts which had the lastComment like the following



                                      $latestCommentPosts = Post::whereHas('lastComment')->get()


                                      And filter the latestCommentPosts like the following



                                      $latestCommentPosts->where('active', 1)->get()


                                      Or, you can archive by one query like the following as well.



                                      Post::whereHas('comments', function($q) { 
                                      $q->where('active', 1);
                                      })->get()


                                      Like that, you got all the latest comment with active is 1.






                                      share|improve this answer















                                      According to your question, the Post model has many Comments. And you want to get the comment from the post where active is one and must be the lastest id.



                                      Get the last comment like the following



                                      public function lastComment()
                                      {
                                      return $this->hasOne('comment')->latest()->take(1);
                                      }


                                      Get all posts which had the lastComment like the following



                                      $latestCommentPosts = Post::whereHas('lastComment')->get()


                                      And filter the latestCommentPosts like the following



                                      $latestCommentPosts->where('active', 1)->get()


                                      Or, you can archive by one query like the following as well.



                                      Post::whereHas('comments', function($q) { 
                                      $q->where('active', 1);
                                      })->get()


                                      Like that, you got all the latest comment with active is 1.







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Jan 20 at 9:09

























                                      answered Jan 20 at 9:00









                                      Set Kyar Wa LarSet Kyar Wa Lar

                                      1,68821536




                                      1,68821536






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54274389%2flaravel-get-all-models-that-their-last-relationship-have-some-condition%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Liquibase includeAll doesn't find base path

                                          How to use setInterval in EJS file?

                                          Petrus Granier-Deferre