Posted the below not long ago and received some really good answers however whilst developing, my requirements became clearer. Instead of continually editing my previous post, thought I’d make a new one.
How do I return a single Model when working with nested relationships?
Assuming you’ve read my post above, I need to access the Team Model (not collection) for that particular Match for the logged in user. FYI, I’ve named the Model “Team” and then referenced the hasMany function as “players” to the Match Model.
The Team model contains a few columns such as ‘match_id’, ‘user_id’, ‘team’, ‘team_alias’, ‘goals’, ‘assists’, ‘paid’. I need to be able to access these.
Something like this in mind (I want to use this in my blade):
@foreach($matches as $match) { @if($match->player->paid) some html showing a payment complete @else some html showing payment required @endif } @endforeach
Any ideas on how I can achieve this?
Edit: Adding more details for clarity
My Match Model looks like this:
Match {#645 ▼ #original: array:10 [▼ "id" => 5 "season_id" => 1 "venue_name" => "Wembley Stadium" "venue_address" => "Wembley, Something Lane, London, Postcode" "home_score" => null "away_score" => null "motm" => null "match_date_time" => "2019-11-21 10:00:00" "created_at" => "2019-11-13 23:14:44" "updated_at" => "2019-11-13 23:14:44" ] }
I use the venue_name, venue_address and match_date_time to display a table of all matches available for a user. A few more options I need to display on this table are whether a person has paid or not. This information is stored in the Team table (once a person submits their availability).
The Team model looks like this:
Team {#667 ▼ #original: array:10 [▼ "id" => 37 "match_id" => 5 "user_id" => 2 "paid" => 0 "team" => null "team_alias" => null "goals" => null "assists" => null "created_at" => "2019-11-14 20:48:02" "updated_at" => "2019-11-14 20:48:02" ] }
The Match Model is linked via id to the Team model which contains match_id.
How can I easily access the Team Model for the logged in user from this particular Match model?
Advertisement
Answer
For what i’ve understand, you already have a Match, and a logged user, and you want to find the Team where the logged user play and the Match given right?
Team::where([['user_id', auth()->user()->user_id /*or the User table primary key*/], ['match_id', $match->match_id /*or the Match table primary key*/]])
or, if you have already implement the realtionship from Match and Team inside the Model, you can do something like
$match->teams()->where('user_id', auth()->user()->user_id /*or the User table primary key*/)