I am quite new to Laravel 4 and its great Eloquent ORM. I have four tables such as :
Sector (iSectorCode);
MailingSector (iSectorCode, iMailingCode);
Mailing (iMailingCode);
MailingLanguages(iMailingCode, sTranslation);
I have the sector id, and I want to get all Mailings associated. But I also need to reach the MailingLanguages table containing the content translations for a specific Mailing.
So for now I can get all Mailings for a specific sector doing :
Sector::find($iSectorCode)->mailings()->get()->toArray();
But doing Sector::find($iFormSectorCode)->mailings()->mailingsLanguages()->get()->toArray(); don't work even if the relation between Mailing and MailingLanguages is defined :
public function mailingsLanguages(){
return $this->hasMany('MailingLanguage','iMailingCode');
}
So I don't know how to get all translations for a specific Mailing, for a specific Sector.
Providing that you've setup relationships between all of the tables, you can request that they be grabbed with the initial request.
$sector = Sector::with('mailings', 'mailings.languages')->find($iSectorCode);
This will create a nice join that will include related records for Mailing, then their related records for MailingLanguage, as well as the requested Sector.
The above example does assume that Sector has a relationship called mailings and that Mailing has a relationship called languages.
You could also load them in after the fact.
$sector = Sector::find($iSectorCode);
$sector->load(['mailings', 'mailings.languages']);
I would recommend making use of the findOrFail method that laravel provides.
try {
$sector = Sector::with(['mailings', 'mailings.langauges'])
->findOrFail($iSectorCode);
} catch(ModelNotFoundException $e) {
// do something here
}
This saves having to check whether $sector returned anything, as an exception will be thrown.
Hope that helps.
Related
I'm having a problem. I have tables that relate:
internal_clients->subsidiaries->departments->job_titles->users
I also have their respective models.
My doubt is:
How do I get all the data associated with users from the top of the tree (internal_clients)
?
I'm trying to follow the Laravel documentation using hasManyThrough.
However, in the documentation it explains only how to do it in a chain of three tables. They teach how to place an intermediate table (model) as the second parameter of the hasManyThrough method (BaseClasse::class, IntermediaryClass::class).
However, in my case that has several tables between users and internal_clients, how would I do this? What would be the intermediate table?
I would like to make a query that returns the user's internal_client, subsidiary, department and jobTitle (associated with users).
I'm trying to do it this way:
Model InternalClient
public function users()
{
return $this->hasManyThrough(User::class, InternalClient::class);
}
Controller UserController
public function allRelations($internalClientId)
{
$internalClient = InternalClient::find($internalClientId);
$users = $internalClient->users;
return response()->json($users, 201);
}
The InternalClient id arrives at the controller above.
When I access the route, the error below is returned:
In short: I would like to know if there is a way to get all the data (from all tables that are in this hierarchical tree) that are associated with the User.
I couldn't find an answer on the Stackoverflow PT-BR.
Thank you!
I am new to Laravel but I dont think Im writing optimised code. I am looking at getting all overdue invoices separated by clients. Invoices table and clients table. client_id is within the invoices table. I have the following below but I wanted to know if there is a better way. I would also want to grab the client name from the clients table. I have created an array so I can loop throgh accordingly on the view file, but again im not sure this is the correct way?:
$overdueClients = Invoice::where("date_paid",'0000-00-00')->where("date_due","<=",date("Y-m-d"))->pluck('client_id');
foreach($overdueClients as $overdueClient)
{
$invoices = Invoice::select("title","total","on_account","date","date_due")->where("date_paid",'0000-00-00')->where("date_due","<=",date("Y-m-d"))->where('client_id',$overdueClient)->get();
$return[$overdueClient][] = $invoices;
}
return $return;
yes luckily there is a better way for which term is called relations and can use eager loading so what you can do is to make relation is models first :
so in you Invoice model you write something like below :
public function users(){
return $this->belongsTo('App/Users');
}
you should fix the above relation according to the name and path of your model and in your users model :
public function invoices(){
return $this->hasmany('App/Invoices');
}
so now an invoice belongs to a user and a user can Have many Invoices . and when you need to get the users which has invoices and overdue invoices you do like below :
$users = Invoices::with('users')->where("date_paid",'0000-00-00')->where("date_due","<=",date("Y-m-d"));
this is the better way to act because of preventing n+1 problems this way you only load users if they have overdue invoices if not they are not being loaded at all take a look at documentation below :
https://laravel.com/docs/7.x/eloquent-relationships#introduction
i strongly recommand to take time and read this and practice it as you would need it more that you think when you want to work with laravel . hope this helps
I have a laravel app that allows users to post posts. Each post has a price (stored as an integer), and belongs to a university, which in turn belongs to a country, which has a currency.
Every-time I retrieve the posts, I want to return the currency as well. I could do with('university.country') but that would return all the details for both the university and country.
I could add a getCurrencyAttribute and define the logic there, but that seems not what mutators are for, especially since if I get all the posts, each post will further run two of its own queries just to get the currency. That's 3 queries to get one post, which quickly takes its toll when returning more than 10 posts.
public function getCurrencyAttribute() {
return $this->university->country->currency;
}
public function getPriceAttribute($value) {
return "{$this->currency}{$value}";
}
^ example above: no need for appends because price is automatically overwritten. This is the problem as seen on DebugBar (two new queries are being called on the Post model, which while expected, becomes inefficient when retrieving lots of posts):
What's the best way to get a single related field, every-time?
Full code on GitHub.
You can limit the eager loading columns:
Post::with('webometricUniversity:uni-id,country_id',
'webometricUniversity.country:id,currency')->get();
If you always need it, add this to your Post model:
protected $appends = ['currency'];
protected $with = ['webometricUniversity:uni-id,country_id',
'webometricUniversity.country:id,currency'];
public function getCurrencyAttribute() {
return $this->webometricUniversity->country->currency;
}
Then you can just use Post::get() and $post->currency.
I have a flight class and this flight has a custom view field like so:
This represents a belongs to many relationship which stores website_id / flight_id and pricing as pivot data in a pivot table.
The custom view uses JS to send this data back to the controller in this format:
{"1":{"price_adult":"434","price_child":"545"},"2":{"price_adult":"323","price_child":"324"},"3":{"price_adult":"434","price_child":"43"}}
Trying to send this data with the request doesn't create the relations fields, and because I do not have a flight ID at the point of creating this within the controller I can not loop this JSON to make the relations manually.
Can anyone point out what the best course of action is or if there is support for this? I took a look at the docs but they are woefully short and patchy in terms of being much help.
EDIT:
I should have said I can probably make this work using a custom name attribute on the model for the relation, then add a set mutator to loop this data and update the prices relation but I don't want to go down this route if there is support for this I am missing out of the box in backpack.
EDIT2:
Someone asked about the relation:
$this->belongsToMany(Website::class, 'website_pricing')->withPivot('price_adult', 'price_child');
This is working fine its not a problem with the relation working its how can I get backpack to store the data as a relation when the flight has no ID yet, or how can I pass the data I posted above in such a way that the backpack crud controller can handle it?
You may need to create a flight first, if no flight id is being provided. Can you explain the database relational structure more?
Basically thought I should post what I did because no one could provide an answer to this.
So basically you have to copy the store / update functions from the parent, changing a few lines.
$this->crud->hasAccessOrFail('create');
// fallback to global request instance
if (is_null($request)) {
$request = \Request::instance();
}
// replace empty values with NULL, so that it will work with MySQL strict mode on
foreach ($request->input() as $key => $value) {
if (empty($value) && $value !== '0') {
$request->request->set($key, null);
}
}
// insert item in the db
$item = $this->crud->create($request->except(['save_action', '_token', '_method']));
$this->data['entry'] = $this->crud->entry = $item;
// show a success message
\Alert::success(trans('backpack::crud.insert_success'))->flash();
// save the redirect choice for next time
parent::setSaveAction();
return parent::performSaveAction($item->getKey());
Basically any line which references a function in the parent class using $this->method needs to be changed to parent::
This line is what I used to submit the relations JSON string passed to the controller as relations $item->prices()->sync(json_decode($request->input('prices'), true));
This is done after the line containing $item = $this->crud->create as the item id that just got stored will be available at that point.
I have three tables: users, emails,attachments. User table is connected with emails by user_id. Emails table is connected with attachments by email_id.
My question is: How should I make it look eloquent in laravel to get all users their emails and their attachments? (I know how get all user and they emails but I don't know how to add attachments.)
Depending on your database relationship,you may declare a relationship method in your Email model, for example:
// One to One (If Email has only one attachment)
public function attachment()
{
return $this->hasOne(Attachment::class);
}
Otherwise:
// One to Many (If Email contains more than one attachment)
public function attachments()
{
return $this->hasMany(Attachment::class);
}
To retrieve the related attachment(s) from Email model when reading a user using id, you may try something like this:
$user = User::with('email.attachment')->find(1); // For One-to-One
$user = User::with('email.attachments')->find(1); // For One-to-Many
Hope you've already declared the relationship method in the User model for Email model using the method name email.
Note: make sure, you have used right namespace for models. It may work if you've done everything right and followed the Laravel convention, otherwise do some research. Also check the documentation.