mardi 12 juin 2018

Using whereRaw on pivot relationship model

I need to be able to use a whereRaw on a pivot table relationship to get all the data for today.

For example, this is my model

public function comments(){
        return $this->belongsToMany('App\Models\Comments', 'user_comments', 'user_id', 'comment_id');
}

Which works great, it gets me all the data I need.

But then how would I use a whereRaw statement on this model? So if i needed to loop through every comment that was created today, but the comment date field is stored in Y-m-d H:i:s format so i need to trim off the time, how would i do it? Trying to do something like this

foreach($user->comments->whereRaw('DATE(comment_date) = DATE(NOW())') as $comment){
   echo $comment->content;
}

But it just returns

[BadMethodCallException]
Method whereRaw does not exist.

Is it not possible to use the whereRaw builder like this?

Also how would i do this through a relationships relationship?

For example, if my comments had a relationship to a table called comment_location and I wanted to do a whereRaw on the comment Location relationship like this

foreach($user->comments as $comment){
  foreach($comment->commentLocation->whereRaw() as $location){
    echo $location->name;
  }
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire