make the display order based on another table value - laravel

I have two tables request and status_tracker. I want to list the row in top which has only one entry in status tracker.
I have the query in $user=DB::table('request')->select('request.*)->get();
I want to add the order based on status_tracker table. If request_id has count '2' in status_tracker table I want to display in top of the table
$user=DB::table('request')->select('request.*)(order may happened here)->get();
if ID 19,11,15 has 2 count in status_tracker it should display first and rest of them will display below as 19,11,15,18,17,16,14,13,12,10.
Is it possible by order the row based on another table field count in laravel?

You could use 'withCount' which will add a column named {relation}_count and orderBy with that, so try something like this:.
$user = App\Request::withCount('status_tracker')
->orderBy('status_tracker_count', 'desc')
->get();
You can read more about this on official Laravel docs
Note: Your model relationship should be well established in order for this to work, so make sure you have specified the relations between both tables :D

Related

What is the different between laravel PLUCK and SELECT

I found that laravel 'pluck' return an plain array and 'select' return an object. Can anyone explain it to me have any other different between two this?
thank you.
Pluck is a Laravel Collections method used to extract certain values from the collection. You might often want to extract certain data from the collection i.e Eloquent collection.
While Select is a normal selection of either multi or specific columns. They are
By using Pluck you only ask to return necessary fields, but with get you will pull all columns. Also select does the same & the difference here is between the returning result. Using pluck cause returning the final result as an array with pair of given arguments, but select return an array (or object) which every single child contain one row.
$name = DB::table('users')->where('name', 'John')->pluck('name');
Select
EX : DB::table('users')->select('id', 'name', 'email)
Select is a method sent to the database that Laravel will translate as
SELECT id, name, email FROM users
This will select the data of the columns you asked and nothing else. It allows you to be more efficient with your request by only asking the required data. Take the example above and image that the user is a Facebook user. It has a ton of data on it, plus relations to other tables. If you just want to display the name, email and a link to the user profile, doing this request!
For more info and knowing more about the expected response visit : https://laravel.com/docs/9.x/queries#select-statements
Pluck
EX:
$users = DB::table('users')->where('roles', '=', 'admin')
$emails = $users->pluck('email')
The Pluck method retrieves the values in a collection that you already got from the Database and that is now a Laravel Collection. This allows you to create an array of the plucked data, but will not improve the performance of your request, as in the Example above, the $users would hold all data of all the admin users.
Since it does not improve performance, what good is it then ?
The pluck would be useful for example to separate some datas in different variables depending on where. You might need the users data for some stuffs, but also want to display a quick list of all emails together.
For more info about the pluck method and understand how to create a keyed array from a second column, visit the docs here: https://laravel.com/docs/9.x/collections#method-pluck
Pluck function normally used to pull a single column from the collection or with 2 columns as key, value pairs, which is always be a single dimension array.
Select will return all of the columns you specified for an entity in a 2 dimensional array, like array of selected values in an array.
Note: Pluck function is a collection function which happens after the data is fetched. Select is a query builder function that builds query to perform in the database server.
Actually select is used inside DB queries, which can affect the performance by limiting the pulled columns. However, Pluck is Laravel Collection's method, so you can use pluck after you pull the data from DB.

Laravel Nested Relationship Get List of Ids in Column

I have encounter a problem that I am not able to solve :/
So, I currently have 4 Models: Make > Model > Generation > Version(['engine_type'])
I need to get a unique list of all the fuels (engine_type) that a certain car model has within it's versions. i.e: for $model = Model::find(1) I want all of it's $model->generations()->versions()->get('engine_type') as a list of unique ids so I can know which engine types this car models has!
Thanks in advance!
first step: you should get all generations for the current model, that would be achieved by join table 'models' with table 'generations' ....
second step: join the results with the table 'versions' witch contain the result column we desire to show ('engine_type')
this chain of join should use the foreign keys that represent relations between the tables, so you have to make sure that you setup up your relation well ...
third step: after selecting 'versions.engine_type' use 'distinct()' to make sure there is no duplicate result,
more about distinct in:
https://laravel.com/docs/7.x/queries#selects
$ids= Model::where('id',$modelId)->join('generations','generations.model_id','models.id')
->join('versions','versions.generation_id','generations.id')
->select('versions.engine_type')->distinct()->get();

Laravel - Get values from pivot table column, using pivot tables unique row ID

I'm trying to figure out if there's some way to get the values of two columns in a pivot table, based on a unique incrementing ID that I gave each row.
I have a Job model, a Location model, and an Application model.
The Job and Location have a many to many relationship with a pivot table "job_location". The two foreign keys it contains are job_id and location_id. However, I also gave every row a unique incrementing ID, jobloc_id.
If I only have the jobloc_id, how can I look up the values of the other two columns?
$jobLoc = $location->jobs->wherePivot('jobloc_id', '=', 1);
return $jobLoc->job_id;
Returns "Method wherePivot does not exist" even though I've seen references of people using it. All I have is the jobloc_id, and am trying to lookup the other two values based on this so that I can fully load the Job and Location to pull attributes from them.
Any pointers would be greatly appreciated. This is in Laravel 5.3.
If you're added ID to pivot table (jobloc_id for example) and you want to get row by ID, just use query builder:
DB::table('job_location')->where('jobloc_id', 1)->first();
That's the fastest and simpliest way to do that when you have unique row ID in the pivot table.

How to use field of pivot table

I've two tables user and product, along with their relationship user_product. The relationship table contains an extra field category. Now I want to find
the number of products selected by a user of a particular category.
I've done it in my page through coding. Is there any easier way to do this?
How to use field of pivot table?
you can use withPivot
Ex:
$this->belongsToMany('Role')->withPivot('foo', 'bar');

How to get most repetitive values with Eloquent?

I have relation many to many (posts and tags) in Eloquent. Is it possible to order tags in the pivot table to get 10 most commonly used tags?
Yes it is possible, add some kind of attribute (to the pivot table and update it upon every select from the database. (increment the value)
And when selecting use wherePivot method.
If you want "most recent used", add timestamps to the pivot table in your migration and touch pivot table on every select.
Yes it is actually very simple to do that.
In the table that you store your tags add another column called count_cache(or whatever you want), then every time you add a tag instance to a post instance do a count() of the tag_id in the pivot table and store the value to the count_cache column in the tags table.
Then you can simply get the tags table ordered by the count_cache collumn (descending) with a limit of 10.
If you need further explanation please make a comment :)

Resources