Load model one to many relation eloquent way without primary key but on multiple overlapping fields - laravel-5

I'm working on an older project that I've been tasked to speed up certain parts of while we work on a complete re-write since the code is just badly maintained, poorly written and outdated for what it's suppose to do.
I stumbled into an issue to the core of the project and because of this I can't change it without breaking almost everything else. So I need to load a "relation" the eloquent way (using Planning:with('availability') but there isn't a real foreign ID, it rather laps with multiple fields.
Would there be a way to load it all in one query with the overlapping fields rather than have it load separately creating an n+1 problem?
+--------------+-----------------+
| Planning | Availability |
+--------------+-----------------+
| planning_id | availability_id |
| date | date |
| startHour | startHour |
| stopHour | stopHour |
| candidate_id | candidate_id |
| section_id | section_id |
+--------------+-----------------+
From the above example you can see the overlapping fields are date, startHour, stopHour, candidate_id and section_id.
I tried get...attribute but that still loads with n+1, I tried including it with ->with(['availabilities']) but that doesn't work since I ask for the
model and not the relation:
Edit for more clarity:
Planning Model:
public function availabilities()
{
return Availability::where('section_id', $this->section_id)
->where('candidate_id', $this->candidate_id)
->where('planningDate', $this->planningDate)
->where('startHour', $this->startHour)
->where('stopHour', $this->stopHour)
->get();
}
public function availabilities2()
{
return $this->hasMany('App\Models\Availability', 'candidate_id', 'candidate_id')
}
Controller:
$plannings = Planning::with(['availabilities'])->get();
$plannings = Planning::with(['availabilities2' => function ($query) {
// $this is suppose to be Planning model but doesn't work
$query->where('section_id', $this->section_id)
->where('planningDate', $this->planningDate)
->where('startHour', $this->startHour)
->where('stopHour', $this->stopHour);
// ---- OR ---- //
// Don't have access to planning table here
$query->where('section_id', 'planning.section_id')
->where('planningDate', 'planning.planningDate')
->where('startHour', 'planning.startHour')
->where('stopHour', 'planning.stopHour');
}])->get();

First of all to be able to load my relation I took one of the keys that matched and took the one which had the least matches which in my case was section_id.
So on my Planning model I have a function:
public function availabilities()
{
return $this->hasMany('App\Models\Availability', 'section_id', 'section_id');
}
This way I can load the data when needed with: Planning:with('availability').
However since I had a few other keys that needed to match I found a way to limit this relation by adding a subquery to it:
$planning = Planning::with([
'availabilities' => function ($query) {
$query->where('candidate_id', $this->candidate_id)
->where('startHour', $this->startHour)
->where('stopHour', $this->stopHour);
},
// Any other relations could be added here
])
->get();
It's not the best way but it is the only way I found it not getting too much extra data, while also respecting my relationship

When you want to use multiple fields in where() method you most insert a array in the where() method:
This document can help you
change your code to this:
return Availability::where([
['section_id', $this->section_id],
['candidate_id', $this->candidate_id],
['planningDate', $this->planningDate],
['startHour', $this->startHour],
['stopHour', $this->stopHour]
])->firstOrFail();

Related

Laravel | Polymorphic relationship from morphed model

I am creating a polymorphic relationship which defaults to null, as it doesn't have an association originally.
I then create the association and I want to be able to update the polymorphic table to have a link between the original and the morphed class.
post_images:
| id | post_id | width | height | created_at | updated_at
files:
| id | fileable_type | fileable_id | file_disk_id | created_at | updated_at
So basically, inside of the polymorphic table the type and the id they default to null as it has to be processed first and converted to a standard format etc.
I then create the associated row inside of the morphed table, however I am unsure how to update the polymorphic to have the type and the id from the morphed table.
I have tried to do something like $post->images()->create(...); and then try and do something like $file->where('id', $fileId)->firstOrFail()->associate($post); but this just seems to return null.
So the current process is:
Upload the file -> creates a row in the files table which contains the polymorphic relationships but columns are defaulted to null.
Standardize the file -> the file then gets converted and compressed into a standard format that is used for the site.
Create post_images row -> The site then creates a row for post_images table which then needs to link the update the files row to contain the new polymorphic relation.
Eloquent relationships:
File.php
public function fileable()
{
return $this->morphTo();
}
PostImage.php
public function file()
{
return $this->morphMany(File::class, 'fileable');
}
Post.php
public function images()
{
return $this->hasMany(PostImage::class);
}
I think you should just be able to call the save method on the relationship. For example:
$post->file()->save($file)

Laravel pivot sync() attaches wrong values

I've been dealing with this issue on almost every sync() to the pivot tables where, in Laravel 5.6, when I perform the following it adds one row that is non existent in the request:
$firm_data = request()->all(); // get the request data
$firm = Firm::where('id', request('firm_id')); // get the Firm model
$firm->update($firm_data); // update the model
// add the firm address with a belongsToMany() relationship set on Models\Firm and on Models\Address
$address = $firm->with('addresses')->first();
$addresses = request('addresses'); // get the request data for address
$address->update($addresses); // all ok till here
// deal with the pivot table
// here's the issue...
$address->cities()->sync([request('firm_id'), $addresses['city_id']]);
The firm data and the address data state is saved correctly in the DB, although, the pivot table is filled with two columns instead of one.
I have, in the whole request, one only city_id = 3034856 but to the pivot table it is added the first row firm_id = 1, city_id = 1, "which comes from nowhere":
The pivot table - firm_city
+---------+---------+
| firm_id | city_id |
+---------+---------+
| 1 | 1 |
| 1 | 3034856 |
+---------+---------+
Any thoughts on why this might be happening?
Just to make sure it's right, here the methods for each model Firm and Address:
// On the Firm model
public function cities()
{
return $this->belongsToMany(City::class, 'firm_city');
}
// on the City model
public function firms()
{
$this->belongsToMany(Firm::class, 'firm_city');
}
Thanks in advance for any insight on why this might be happening,
Remove the firm_id:
$address->cities()->sync([$addresses['city_id']]);
Eloquent gets the firm_id from $address, you don't have to specify it.
If you specify
it, Eloquent assumes that you want to sync a City with id=1.

Trying to achieve a hasManyThrough type relationship

I'm trying to achieve something that is similar to Laravel's hasManyThrough, but I'm not sure my DB is set up appropriately or I'm just missing something.
I am trying to display a page for admins to show all of the sites we support. I would like to have a simple column that shows a distinct count of how many customers are attached to each site. To do this, I was going to go through the orders table and retrieve a distinct list of users, then simply use the ->count() method inside my view.
Here is my DB setup (simplified):
sites table (primary key: 'id'):
id | ...
users table (primary key: 'id'):
id | first_name | last_name | ...
orders table (primary key: 'order'):
id | order | user_id | site_id | ....
Site model:
public function customers()
{
return $this->hasManyThrough('App\User', 'App\Order', 'site_id', ' id')->distinct();
}
I realize right away that the key difference between my DB setup and the documentation is I do not have an order_id in my users table, but it doesn't make sense that I do since a user can have many orders.
It is worth noting: I also have a table user_orders. I'm not sure if I should be using that instead. user_orders has the following set up:
id | user_id | order
You can see that it is simply an intermediate table to hold connections between users and orders (remember order is the PK in orders, not id).
So, can anyone help me understand what I am doing wrong?
You could get away with a Join. I give you this sample code to guide you
public function customers()
{
return $this->hasMany('App\Order')
->leftjoin('users', 'users.id', 'orders.user_id')
->groupBy('users.id'); //Is this needed?
//Above code will return you a collection of Order though, but with the user data.
//Let's try using the User model
return App\User::whereHas('orders', function($query) use ($this->id) {
$query->where('site_id', $this->id);
})->get();
}

Joining an additional table with belongsToMany()?

This question is best illustrated by an example:
users
id
name
roles
id
name
role_user
user_id
role_id
rank_id
group_id
...
ranks
id
name
groups
id
name
I can easily eager load a users table by specifying the following relationship in my User.php model:
public function roles() {
return $this->belongsToMany('Role');
}
Which will output the table below when calling User::with('roles'):
User | Role
-------------
Jon | Admin
Jan | Mod
However I have no idea how to extend this to include:
User | Role | Rank | Group
-----------------------------
Jon | Admin | Boss | Blue
Jan | Mod | Minion | Red
What I've tried doing User::with('roles', 'ranks', 'groups') but that is certainly wrong since I'm telling Laravel there are rank_user and group_user intermediate tables too but there aren't. What is the correct way?
PS: I know it's better to separate the ranks and groups into their own relationship/pivot tables, this is simply an example.
EDIT: Closest example I can find for this: https://github.com/laravel/framework/issues/2619#issuecomment-38015154
You can just treat your model's relations methods as ordinary queries and build upon them:
public function roles() {
return $this->belongsToMany('Role')
->join('role_user', 'role_user.role_id', '=', 'roles.id')
->join('ranks', 'ranks.id', '=', 'role_user.rank_id')
->join('groups', 'groups.id', '=', 'role_user.group_id');
}
Relations queries like the above are not so intuitive to understand when they get too complex, so it may be better to rethink database design, but in theory it's possible to manipulate them.

Laravel 4: one to many by on multiple columns?

I'm making a table that essentially maps rows in a table to rows in another table where the structures are as follows:
|--- Words --| |- Synonyms -|
|------------| |------------|
| id | | id |
| en | | word_id |
| ko | | synonym_id |
| created_at | | created_at |
| updated_at | | updated_at |
|------------| |------------|
Now then, I know I can essentially have the words model have many Synonyms through a function like:
public function synonyms()
{
return $this->hasMany('Synonym');
}
No problem, but this method always gets it by the the word_id, and I would like to get it from word_id OR synonym_id that way I don't have to make multiple entries in the DB.
Is there anyway I can do this?
Check laravel docs Eloquent relationships. It would only get word_id because that's the only foreign key I believe.
Also why do you have synonym_id in your Synonyms table?
I believe you are looking for polymorphic relationship.
http://laravel.com/docs/eloquent#polymorphic-relations
I think your best bet is to create a many-to-many relationship with words on itself using the synonyms table as your pivot table.
Add this to your Word model.
public function synonyms()
{
return $this->belongsToMany('Word', 'synonyms', 'user_id', 'synonym_id');
}
Using it:
$word = Word::where('en', '=', 'someword')->first();
foreach($word->synonyms as $synonym) {
// This method would probably return the same word as a synonym of itself so we can skip that iteration.
if($synonym->en == $word->en) {
continue;
}
// Echo the synonym.
echo $synonym->en;
}
I'm a bit confused on you wanting to be able to find synonyms by the word_id or synonym_id but I think if you are using the many-to-many, it won't matter because if you know the synonym, it's still technically just a word, and you'd do the exact same thing.

Resources