I am new to laravel. I am trying to build a relationship between two tables.
my database tables
comments table
$table->increments('id');
$table->text('comment');
$table->string('shop_name','80');
$table->bigInteger('product_id');
$table->timestamps();
comments_images table
$table->increments('id');
$table->bigInteger('comment_id');
$table->string('images','255');
$table->string('shop_name','80');
$table->timestamps();
=========================
Comment model
public function images()
{
return $this->hasMany(Comments_images::class,'comment_id');
}
Comments_images model
public function comments()
{
return $this->belongsTo(Comment::class);
}
I tried to return related data like this
return Comments_images::find(439)->comments()->get();
return Comment::find(880)->images()->get();
return (new Comment())->images()->get();
None of them work!
What should I do?
Are you utilizing the namespace correctly? For example, 'App\\Comments_images'.. Also, models are best left singular- for example, 'Comment' or 'Comment_Image'. I bring that up because you aren't being consistent, which may be causing the error. The last thing is to use a string of the class, not returning an actual class. See the below examples, and notice capitalization and that I don't put an 's' on some things..
// in Comment model
public function images()
{
return $this->hasMany('App\Comments_Image','comment_id');
}
// in Comments_Image model
public function comment()
{
return $this->belongsTo('App\Comment', 'id', 'comment_id');
}
Edit: Feel free to use Comment::class
instead of the string 'App\\Comment'
- It resolves to the same thing and works better with editor navigation, autocomplete, and other helpful things.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.