Search code examples
phplaraveleloquent-relationship

How to create a laravel relationship model with a SQL query like this


I have query like this

SELECT * FROM 'discussions' INNER JOIN comments ON comments.commentable_id = discussions.id WHERE discussions.user_id = 1 ORDER BY comments.id DESC

How to create relationships in laravel models

Not with query builder like this

DB::table('discussions')
    ->join('comments', 'comments.commentable_id', '=', 'discussions.id')
    ->where('discussions.user_id', '=', 1)
    ->orderBy('comments.id', 'DESC')
    ->get();```

Solution

  • First you need to know what type of relationship it is.

    One:One, One:Many, Many:Many, Many:One

    After that you can take a look at the documentation

    You create 2 models by calling to php artisan make:model <name> within your terminal, or by manually creating them.

    After that you just do whatever documentation tells you to do.

    Say you have one-to-many where one discussion has many comments, it is important you specify the foreign_key in the 2nd parameter if it's non-conventional naming.

    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Discussion extends Model
    {
        /**
         * Get the comments for the discussions post.
         */
        public function comments()
        {
            // Watch the foreign_key in this instance 'commentable_id'
            return $this->hasMany(Comment::class, 'commentable_id');
        }
    }
    

    After that you can call something like

    $comments = Discussion::where('user_id', 1)->first()->comments
    

    To get all comments belonging to that discussion

    I don't want to be a jerk, but the documentation is truly a wonderful source of information. And I advice you to read everything before starting your development journey.