0

I have a polymorphic relation between organizations and ratings. My ratings table is set up like so:

id - integer
user_id - integer
score - integer
ratable_type - text
ratable_id - integer

Calling $org->ratings will retrieve an array with all ratings associated with that specific org. However, I only want to see if there is a rating with a specific user_id value.

Basically, I want to retrieve the rating with user_id = Auth::user()->id. Is this possibly without looping through all the ratings to see when $org->rating->user_id == Auth::user()->id?

2
  • You need to fetch the related ratings and then check or rather do simple check with db query? Commented May 30, 2014 at 8:43
  • I ended up using Rating::where('user_id', '=', Auth::user()->id)->where('ratable_type', '=', 'Org')->where('ratable_id', '=', $org->id)->first(), but is there a more succinct way to do this? Commented May 30, 2014 at 18:13

1 Answer 1

1

If you don't need to load the relation, then simply query the DB:

$org->ratings()->where('user_id', Auth::id())->first();
// returns Rating model or NULL

// in previous versions of the framework (if Auth has no id method)
$org->ratings()->where('user_id', Auth::user()->id)->first();

Otherwise filter the collection:

$org->ratings->first(function ($key, $rating) {
     return $rating->user_id == Auth::id();
});
// like before: Rating model or NULL
Sign up to request clarification or add additional context in comments.

1 Comment

Using $org->ratings()->where('user_id', Auth::id())->first(); worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.