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?
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*/)
Related
My laravel application is built on Laravel 8.12 and uses pest php for tests,
I have two tables groups and meetings and the their relation is one to many, where a meeting belongs to a group and group has many meetings,
I have a test case where I have to assert if a group can be created successful with it's meeting, the test case works well if I create only group without it's meeting but if I create the group with it's meeting using their relation the groups table contains two records of groups instead of one.
This is my test case when I create only group record
test('user see all meetings and registered groups successful', function () {
Group::factory()->create();
dd(Group::pluck('id'));
actingWithPermission($this->user, $this->permission)
->get($this->route)
->assertViewHasAll([
'totalRegistered' => 1,
'totalMeetings' => 1,
]);
});
When I create the group record the groups table contains only one record as shown below
^ Illuminate\Support\Collection^ {#3995
#items: array:1 [
0 => 36
]
#escapeWhenCastingToString: false
}
Test case when I create group and it's meeting record
test('user see all meetings and registered groups successful', function () {
Group::factory()
->hasMeetings(1)
->create();
dd(Group::pluck('id'));
actingWithPermission($this->user, $this->permission)
->get($this->route)
->assertViewHasAll([
'totalRegistered' => 1,
'totalMeetings' => 1,
]);
});
When I dump the database contains two records of the groups instead of 1 as shown below:
^ Illuminate\Support\Collection^ {#1847
#items: array:2 [
0 => 36
1 => 37
]
#escapeWhenCastingToString: false
}
This is one to many relation ship between group and meetings
public function meetings()
{
return $this->hasMany(Meeting::class);
}
How can I fix this?
I have users that can have multiple parameters. These are called for example user_param_1, user_param_2, ..., user_param_n. This is dynamic. It is a separate table user_parameters, which stores id, user_id, name and value. The relationship is a belongsTo and hasMany between Users and UserParameters. The problem is:
When editing, I want to keep it dynamically and if the user has an user_param_n+1, it should be created. But I already have problems to write the condition for the existing parameters.
I create myself an userParameters array, which contains from the $request variable only the necessary parameters. The array looks like this:
[
0 => [
"name" => "par1"
"value" => "var1"
]
1 => [
"name" => "par2"
"value" => "var2"
]
2 => [
"name" => "par3"
"value" => "var3"
]
]
Then I want to save it. My controller knows the user, so I can access to $user->id.
foreach ($userParameters as $userParameter) {
$user->parameters()->updateOrCreate(['id' => $user->parameters->id, 'user_id' => $user->id], $userParameter);
}
The issue is, that $user->parameters is an array of eloquent models. The condition is wrong. I can't access id directly. But how I can solve it? I need something like "['id' => [IF-DATABASE-ID-EXISTS-IN-ARRAY-$user-parameters]"... but how in an eloquent way?
Thanks in advance!
Best regards
I think you need to get the existing parameter using user_id and parameter_name cuz it's the uniqueness of that parameter row, if there is no parameter with this name it will create it with user_id & parameter_name and parameter_value passed to updateOrCreate function
foreach ($parameters_from_request as $parameter) {
$user->parameters()
->updateOrCreate(
[
'name' => $parameter['name'] ,
'user_id' => $user->id
],[
'name' => $parameter['name'],
'value'=> $parameter['value']
]);
}
I would like to create a junction table tbl_guid_cost_centre that gets taken care of without me manually saving it to the database. I tried adding this to my relations:
'costCentre' => [
self::HAS_ONE,
'CostCentre',
'guid_to',
'foreignKey' => 'guid',
'tbl_guid_cost_centre(guid_to, cost_center_id)',
"order" => "id desc"],
so that my when saving the costCentre, a row is created for it in my tbl_guid_cost_centre. However I'm getting the error:
Property "CHasOneRelation.0" is not defined.
Any suggestion?
You can have your junction table with the keyword through in your relations:
public function relations() {
'guidCostCentre' => [
self::HAS_ONE,
'GuidCostCentre',
['guid_to' => 'guid']
],
'costCentre' => [
self::HAS_ONE,
'CostCentre',
'cost_centre_id',
'through' => 'guidCostCentre'
]
}
You're defining HAS_ONE relation in a wrong way. The first three elements of relation configuration array should be: relation type, related model name and foreign keys definition. All further elements should be indexed by keys related to relation properties. 'tbl_guid_cost_centre(guid_to, cost_center_id)', probably generates this error, because it does not have a key, so it is treaded as a value for 0 property. You didn't share any details, so it is hard to guess what you want to achieve, but you should start from something like this:
'costCentre' => [
self::HAS_ONE,
'CostCentre',
'guid_to',
'order' => 'id desc',
],
And add additional settings at the end array with correct key.
Some examples and explanation you can find in the documentation: https://www.yiiframework.com/doc/guide/1.1/en/database.arr#declaring-relationship
as you see in the title,when i using tymondesigns/jwt-auth to authenticate the HTTP requests, i generated the token with a record of table user,and then when i authenticate the request,i found that the action of 'authenticate' to find a record at the table 'users' that's not i want.
here is the query sql:
array:1 [
0 => array:3 [
"query" => "select * from `users` where `users`.`id` = ? limit 1"
"bindings" => array:1 [
0 => 1
]
"time" => 0.39
]
]
so,my question is:
how to set up the table i want when i do things both generate a token and authenticate, thanks!
As given in their wiki page, you can use "user" option to specify the Model name which you want to use in config/jwt.php.
User model path - user
This should be the namespace path that points to your User class.
Lets say that i have the following associations schema:
Person => [
hasMany => [
Courses => [Person.id = Courses.person_id]
],
Courses => [
belongTo => [
Schools => [School.id = Courses.school_id]
]
When I view a person through mydomain/person/view/1 I need to have a table to show the Courses of that Person. Inside this table each Course need to show the name of the School.
So I tried the following on my controller:
public function view($id = null)
{
$person = $this->Persons->get($id, [
'contain' => [
'Courses.Schools',
]
]);
$this->set('persons', $test);
$this->set('_serialize', ['person']);
}
What I get on view is:
Person => [
firstname => test,
lastname => test,
courses => [
0 => [
id => 1,
shool_id => 1,
person_id => 1,
]
]
]
There is no school in the array although I used it in the contain option. So I can't display the name of the school. Am I doing anything wrong? Is there any guideline how can I show these fields on the view.
Basically I am sorry for this. This is a caused because of the debugKit. The debugkit is showing through the variables panel the associations only until the level I have mentioned but I used a var_dump and saw that the associations and the related fields are fetched/loaded correctly. I trusted the debugKit and I thought that they where not loaded.