There is a users table and tickets are linked by the users.id = tickets.create_by . To fetch a user from a particular ticket, I wrote the code:

 class Ticket extends Model { protected $table = 'tickets'; public function user(){ return $this->hasOne('App\User','id','create_by'); } } 

use : Ticket::find(1)->user

How to implement a sample so that when writing Ticket::all()->withUsers() I can get a list of all tickets with users.

Addition to the question : At the moment there are many connecting fields ( foreign keys ) in the table, how to implement sampling through models so that the data on the keys are pulled together with the records ( tickets ). Of course, you can simply implement the request, but whether it will be correct and you don’t really want it because it’s sure that you can do better.

ps I will be glad to several options for solving this problem.

    1 answer 1

    This is called Eager Loading - when you want to immediately get data from related tables:

     $ticketId = 123; $ticket = Tickets::with('user')->find( $ticketId); $user = $ticket->user; 

    In with() you can list several relationships:

     $ticket = Ticket::with('user','event','promocode')->find( $id); 

    For multi-level relationships, point-as-separator is used:

     $ticket = Ticket::with('user','event.city')->find( $id); 

    PS it is better to call the class in the singular - because it is a single ticket: not Tickets , but Ticket . Here you have a well-named User class :)

    • Is there a way to use the Tickets::all()->with('user') construct? - Shadow33
    • @ Shadow33 no such option. The fact is that with() returns a Query Builder object - just like, for example, all sorts of where() - very roughly speaking, this all constructs a SQL query. And all() already returns the records themselves, as well as get() or first() - the output is an array with the result objects. - Sergiks
    • Then such a question if the table has a lot of binding fields, that is, an index from another table. How to proceed with a subdivision so that when a function is requested to return all records with all the data I do not want to write just request, although you can. - Shadow33
    • @ Shadow33, have you tried to read the documentation by reference in the answer, or at least the code of the examples in it? There is also: $books = App\Book::with('author', 'publisher')->get(); for multiple relationships and $books = App\Book::with('author.contacts')->get(); for multi-level. - Sergiks