Khirad Zahra
Khirad Zahra

Reputation: 893

Override primary key with foreign key in hasMany relation using laravel

Here are my tables

Posts

id | name | created_At

Comments

id | comment | post_id | created_at

Post Model

function comments(){
      return $this->hasMany('App\Models\Comment','id','post_id');
 }

PostsController

function index()
{
    Post::with('comments')::get();
}

Now how can i get list of all posts along with comments?

I am trying to match post_id in the child table.

Upvotes: 0

Views: 481

Answers (1)

Saurabh Mistry
Saurabh Mistry

Reputation: 13669

In Your Post Model:

   public function comments()
    {
      return $this->hasMany('App\Model\Comment');
    }

In Your Post Controller :

use Illuminate\Http\Request;

function index(Request $request)
{
    $posts=Post::with('comments')->get();

    // in json
    return response()->json($posts);

    // in your view
    //return view('viewname')->with('posts',$posts);
}

Upvotes: 2

Related Questions