DMS-KH
DMS-KH

Reputation: 2797

How to use one to many relation in Laravel?

I'm beginning to use Laravel Model relationship. But now I don't know how to used that relationship as below function

 class Notification extends Model{

   public function getNotification() {

        return self::select('*')->join('users','users.id','=','Notification.n_user_id')->get();
    }
   }

Upvotes: 0

Views: 37

Answers (2)

vsogrimen
vsogrimen

Reputation: 456

Try this:

class User extends Model
{
    /**
     * Get the Notifications for the User.
     */
    public function notifications()
    {
        return $this->hasMany('App\Notification');
    }
}

But I see in your code that the foreign key field of User ID is named n_user_id you should changed it to user_id to link them

How to use:

$notifications = App\Post::find(1)->notifications;

foreach ($notifications as $notification) {
    //
}

here is a useful Link in Laravel 5.2 Docs

Bonus:

You can also get the User of the notification:

class Notification extends Model
{
    /**
     * Get the User that owns the Notification.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

Upvotes: 1

shakpit
shakpit

Reputation: 23

I have used the following way and hope it'd be helpful.

public function getNotification() {
    $data = DB::table('users')
            ->join('Notification', 'users.id', '=', 'Notification.n_user_id')
            ->select('users.*', 'Notification.*')
            ->where('users.id', '=', 5)
            ->get();
    return $data;
}

Upvotes: 0

Related Questions