Getting data from multiple tables via Laravel Eloquent - laravel

I have three tables; rate_params, review_form_languages, and review_form_translations. And corresponding models RateParam, ReviewFormLanguage and reviewFormTranslation.
rate_params has columns id, info_message, order and validation.
review_form_languages has id and name
review_form_translations has id, rate_params_id, review_form_languages_id, and text.
I would like to have query that fetches all the data from rate_params and the text from review_form_translations where review_form_languages.name is the passed parameter.
I have a query that fetches all the data from RateParam model as below
$reviewForm = RateParam::select(
'rate_params.id',
'rate_params.validation',
'rate_params.info_message',
)->orderBy('order', 'asc')->get()->toArray();
How do I join to get the text from review_form_translations where review_form_languages.name is the passed parameter?

Can you try this ,
use DB; // Top of the file
$reviewForm = DB::table('rate_params')
->join('review_form_translations','rate_params.id','=','review_form_translations.rate_params_id')
->join('review_form_languages','review_form_languages.id','=','review_form_translations.review_form_languages_id')
->orderBy('rate_params.order', 'asc')
->get()
->toArray();

Related

I want to extract the first five data that match the where clause from Laravel relationships

I'd like to do something like this with Laravel's Eloquent:relationship, but it doesn't work.
$playlist->setRelation('tags', $playlist->tags->where('privacySetting', 'public')->take(5));
It works without where clause, but I want to retrieve the first 5 data in the tags relationship table that match the where clause.
How can I do this?
Laravel version is 7.28.1.
this will select top 5 based on criteria from model
$playlist = Playlist::with(['tags' => function($filter){
return $filter->where('privacySetting', 'public')
->take(5);
}])
->get();
//try dd($playlist);

Laravel eloquent with relation data (Eager Loading)

I have two database tables items and measurement_units - item has measurement unit.
Now the problem is I want to select a particular column from items and some column from measurement_unit. I want to use Eager loading
e.g.
$items_with_mu = Item::with("measurement_unit")->select(["item_name", "item_stock"])->first();
When accessing measurement_unit. It returns null. Without the select function it returns data(measurement_unit).
$items_with_mu->measurement_unit;
can anyone help me and sorry for my English.
Try this
Item::with(['measurement_unit' => function($q) {
$q->select('id','unit_column'); //specified measurement_unit column
}])
->select('id','measurement_unit_id','item_name')
->get();
If your laravel version is >=5.5 then you can write in a single line
Item::with('measurement_unit:id,unit_column')
->select('id','measurement_unit_id','item_name')
->get()
You have to select the primary column of the main model like below.
items_with_mu = Item::with("measurement_unit")->select(["item_name", "item_stock", "primary_key"])->first();

Lean Eloquent Results ->with() Eager Loading

I have a query I am working on that feeds into a javascript engine where there is a lot of information returned that isn't used in the javascript. The results are over 1MB and some of that is because of some eager loading. Here is the query:
$customers = Customer::where('customers.office_id', $officeid)
->where("customers.parent_id", null)
->with('lastAppointment')
->with('nextAppointment')
->select("customers.id","customers.family_id", "customers.gender", "customers.family_size", "family_value")
->get();
The relationship of lastAppointment creates a returned nested object with all the columns from the appointments table, where I really only want a single column of start_at
If I do a ->leftJoin() I can limit my results using the final select like this:
->leftJoin(DB::raw("(select customer_id, MAX(start_at) as lastAppointment from appointments group by customer_id) as appt"), 'customers.id', '=', 'appt.customer_id')
->select("customers.id","customers.family_id", "customers.gender", "customers.family_size", "family_value", "appt.lastAppointment")
I am just wondering if there is a way of doing something similar using ->with()?
You can use this code
->with('lastAppointment:_relation_id,start_at')
where _relation_id is customer_id or primary key of lastAppointment correspond model: depends on your table relation. See docs part of Nested Eager Loading
https://laravel.com/docs/5.5/eloquent-relationships#eager-loading p
The with function will accept a callback as the array value of the relationship key. You then have access to the underlaying query builder instance, I think this is what you want:
->with(['lastAppointment' => function($query) {
return $query->latest()->select('customer_id', 'start_at')
->groupBy('customer_id');
}])

Join query in laravel with data manipulation send to view

I am having 2 tables, users and profiledetails
I am able to run Join query and access the data and send to view.
But when I am manipulation the field 'dob' (date format) in profiledetails table. No Success, Please check the code below ,
webpagesConroller:
$users = DB::table('users')
->join('profiledetails', 'users.id', '=', 'profiledetails.user_id')
->select('users.*', 'profiledetails.dob')
->get();
$age = $users->dob->diffInYears(Carbon::now());
return view('webpages.index',compact('users'))->with($age);
View:
<li class="cate_head">Age : {{ $age}}</li>
Error:
Trying to get property of non-object
I have model Profiledetails added the mutators as below,
public function getAge(){
return $this->dob->diffInYears(Carbon::now());
}
public function getDOB(){
return $this->dob->format('d-m-Y');
}
Can I not use this method on another controller for Ex- webpagesController, If yes How.
Since you are using a raw query, the data returned is not an object but an array with the data.
Also you did not limit the query, meaning it could return multiple rows.
You'll probably need to get the data from the $users as:
//with the possibily of multiple rows. Index is the row which has to be used
$users[index]['dob']
//when you are sure it only returns one row
$users[0]['dob'] // or $users['dob'] not sure as of the moment
You want to check the differences with Carbon.
So you will probably need to make a Carbon object of the dob result and check it against the Carbon::now.
$age = Carbon::createFromFormat('Y-m-d', $users[0]['dob'])->diffForHumans();
// diffForHumans() uses the local time
Note that this only gets the age for one row (the index or the first because of [0]).
If you want to do it for every row use a for or foreach where you set the $users->age for every $user. But as these are not object/models but raw data, this will not work.
Hope this helps your question a bit

Eloquent query: Retrieving data from two related models having Same column names

Following gives the list of ID's of SectionDetail Model while I need List of ID's of Section Model:
SectionDetail::with('section')->where('class_id', '=', Input::get('grade_id'))->lists('id');
Problem is both Models SectionDetail and Section has columns "ID".
How can I point to the ID of SectionDetail and Section Model in my Query
You can't do that this way, since there are 2 separate queries fetching SectionDetail and Section.
In order to get Section ids you need to query that model filtered by the relation constraint:
$gradeId = Input::get('grade_id');
// assuming sectionDetails is relation name on the Section model
$sectionsIds = Section::whereHas('sectionDetails', function ($q) use ($gradeId) {
$q->where('class_id', '=', $gradeId); // use prefixed column name in case it's ambiguous
})->lists('id');

Resources