Laravel Eloquent model data from 2 tables - laravel

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).

Related

Eager loading relations for only a subset of records in a Laravel collection

I'm working on a legacy Zend 1 project that's in the process of migrating to Laravel via the Strangler Pattern, and I'm using Eloquent for some of the database queries (though not all as they're still in the process of being migrated). Because Zend 1 can't work on any version of PHP higher than 7.1, it's stuck on the version of Eloquent from Laravel 5.8 until further notice.
I have one particular table containing navigation items, which has a nullable polymorphic relation for content items that uses a morph map to map the Eloquent models to the item types. One type, static doesn't have an Eloquent model assigned to it since it's just a container for other navigation items. Trying to eager load the relation on any items with the static type breaks it because it's not defined in the morph map, and setting it to null doesn't resolve the issue either.
Right now I load the items with a link type of static in a separate query and merge them with the query that gets the remaining navigation items, but this means there are two separate queries and that's not great for performance. Using a union doesn't resolve the issue because the eager load is a separate query from the one for the navigation items.
I know that it's possible to call load() on a collection after it's already been retrieved via a query in order to eager load a relation, and that it's also possible to constrain the eager load so that, for instance, a WHERE clause can be applied when loading the relation. What I'm trying to find is a means to ensure that the query only attempts to eager load the relation if the item type is not static. In other words, constraining not the query to get the relation, but excluding that record from the query so no attempt is made to retrieve the non-existent relation for that record.
Does anyone know if this is possible? One solution I can think of is to split off the items that aren't static in collections and apply load() there, but that's rather cumbersome and I was hoping there was a more elegant method.

How to use multiple tables in one model?

How to add multiple tables in one model without creating new model.
Is this standard practice to use same in laravel-lumen.
Or should I create 50 models to work on 50 tables.
You can't use multiple table in one model. Each model is written for a specific table.
https://laravel.com/docs/5.7/eloquent#introduction
Laravel uses Eloquent Object Relational Mapper. So each model is like a class representation having methods to do query underneath.
You have to create 50 models if you have 50 tables, or at-least for the tables you are using in your application. TO save time, go for plugins like this which would generate eloquent models based on your database structure. Also check another plugin if it helps.
It's not possible.
Each table should have their own model. But it isn't necessary all the times to make a model for each table. Investing some time on making model will help a lot in future work.

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.

How to create models for dynamically generated tables (on the fly)?

I stumbled upon this problem today. My project has a few tables, for which I have created their dedicated Models. However, my project allows user to create dynamic tables.
How do I create relationships or models for/between these dynamically generated tables?
I would not recommend to create Eloquent Models on dynamically generated tables, because Eloquent Models are here to help developers with already created database tables (features like relationships, scopes, attributes casting are usually defined for existing database tables).
What would be my recommendation? Use the Query Builder instead. You will have almost the same functionalities of Eloquent Models, except without model.
Instead of having something like:
DynTable::where('foo', 123)
->where('bar', 456)
->first();
You will have the following:
DB::table('dyn_table')
->where('foo', 123)
->where('bar', 456)
->first();
Basically, the same. But, with the benefit that you can specify any table name to the Query Builder, but you can't change the table name to an Eloquent Model (in a running script).

Resources