Skip to content
Eustáquio Rangel edited this page Jun 3, 2014 · 1 revision

Previous: Collections - Next: Scopes

Has many

We can use has many this way:

    <?php
        User::hasMany("tickets");
        $user = User::find(1);
        foreach($user->tickets as $ticket)
            echo "ticket number ".$ticket->id."\n";
    ?>

The user model will search the user who satisfies the condition (with find(1)), return it to the $user variable, where we can ask for the tickets collection. The User model search for a class with the same name as the relation (tickets), remove the final "s" to get the class name (if needed, we can use pluralization through inflections, please check the models page) and capitalize it. If we want to specify the correct class name, we can use:

    <?php
        User::hasMany("tickets",array("class_name"=>"Ticket"));
    ?>

To load results from Ticket, is searched on the tickets table for an attribute with the name of the current class (User), using lower case (if ignoring case), with _id appended on the end, on this case, user_id, and loaded all the tickets with the current User primary key value, on this case, id.

Belongs to

We can use belongsTo this way:

    <?php
        Ticket::belongsTo("user");
        $ticket = Ticket::first();
        $user   = $ticket->user;
        echo $user->name;
    ?>

The same rules as hasMany are working, for class "pluralization" (you know what I mean). On the case above, Ticket will search for the current user_id attribute on the id attribute on table users.

Has one

We can use hasOne this way:

    <?php
        User::hasOne("account");
        echo $user->account->number;
    ?>

The default behaviour is the Account table having a user_id attribute.

Previous: Collections - Next: Factories

Clone this wiki locally