Laravel - Getting a collection from a table using "join" clause - laravel

LaraCSV uses Laravel Collections to easily export csv files from an Eloquent Model. The table I'm extracting the CSV from has 3 FKs from another table. The fields are ['Operator','Supervisor','Escort'] which relate to the PERS_ID from another table.
I need to create a Collection that considers the join clause needed for these 3 fields to contain the full name of the workers, instead of just the PERS_ID.
I've tried the following:
$excesos = ExcesosVelocidad::all();
Which gives me a Collection but does not allow me to perform the JOIN clause needed to bring the full names of the workers. Is there a way to do this?

You can use joins like this:
$excesos = ExcesosVelocidad::join('x', 'x.x', '=', 'x.x')->get();

Related

Laravel get collection of created/updated rows

new to laravel.
My use case:
Update multiple rows (say: resources table).
Create multiple users (users table).
Retrieve ids of created users
What I currently did:
First, Update the resources table whereIn('id', [1,2,3,4]). (Update eloquent)
Second, Get array of the updated resources (Another eloquent: Resource::whereIn('id', [1,2,3,4])->get()->toArray())
Bulk create a users. Refers to the resources collection above. (Another eloquent: User::create($resources))
Lastly, get the ids of the created users (Not resolved yet. But I might have to use another eloquent query)
All in all, there are 4 Eloquent queries, which I want to avoid, because this might have performance issue.
What I wanted to do is that, On first step(Update), I should be able to get a collection of models of the affected rows (But I can't find any reference on how to achieve this). And then use this collection to create the users, and get the users ids in one query with User::create() so that I will have 2 queries in total.
There is no need to invent performance problems that do not exist.
Update or Insert return only count of affected rows. Commands Select, Insert, Update performed separately. This is a SQL issue, not Laravel.
For single inserts (if you want add one row) you can use insertGetId method of a model.
For example,
$id = User::insertGetId([
'email' => 'john#example.com',
'name' => 'john'
]);
But you get only ID of record. You need to run select to get full data of the row.
To save multiple records with one query you can use
DB::table('table_name')->insert($data);
Since this won't be an eloquent method, you should pass all the columns including created_at and updated_at.
I don't know what is the method name for update.

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 - How to relate two collections like Eloquent method "belongsToMany" and "with"

How can you combine two collections, one being the collection of parent items together combined with your collection of child items?
I would like something like using the method with and belongsToMany,but in this scenario I cannot use both methods correctly because one table is in another schema and the pivot table is in another schema.
Area::with('permissoes')
->where('sistema', '<>', 'S')
->get()
Most Eloquent eagerloads are done with separate queries that just use an IN statement on keys from the previous one. Pivot tables are the exception. It sounds like you need to explicitly tell the Model relation what database your pivot table is in. See my answer here: belongsToMany relationship in Laravel across multiple databases

Laravel Eloquent ORM - Get first and third table data

Category Table
Service Table
Branch Table
I have 3 tables link together. Above is my code, I want to produce the result same as below. Can I use a line of code to do that?
Or I have to get result from 2 tables first then only get the Branch table?
Thanks.
If you would like to obtain a collection of categories with service and branches you can eager load them in a single eloquent query.
$categories = Category::with('service.branches')->get();
But you still have to write a bit more if you would like to achieve your requirement.
Fractal Transformers might help you to do this. See their documentation here.

Laravel Eloquent model data from 2 tables

I've just started using Laravel and I'm coming from a different system using an existing database. In this system there are 2 users table, one stock with the CMS and one custom one.
I want to create an Eloquent model which retrieves data from both tables into one model. I know I can use the following to create a relationship.
$this->hasOne('App\SecondUser', 'id', 'id);
But this results in 2 sql queries, and I want to join results from 2 tables before returning the model, in one join statement. How do I do this?
That might be a bit more complicated that you would expect.
First of all you have to use \DB facade to join the two collections(arrays) and then recreate the Eloquent collection from these arrays using Collection's make method.
More info about the Collection class here
An easier way might be to join them using standard laravel relationships and user something like Model::user->with('relation')->get.
But this will still create 2 queries (still relatively fast).

Resources