简体   繁体   English

laravel 雄辩的关系不起作用

[英]laravel eloquent relations doesn't work

I am new to laravel.我是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 comment_images 表

        $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 Comments_images 模型

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'.例如,'App\\Comments_images'.. 此外,模型最好保留单数 - 例如,'Comment' 或 '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..请参阅下面的示例,并注意大小写,并且我不会在某些事情上加上“s”。

// 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.编辑:随意使用Comment::class而不是字符串'App\\Comment' - 它解析为相同的东西,并且与编辑器导航、自动完成和其他有用的东西一起使用效果更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM