php - laravel Eloquent 关系不起作用

标签 php mysql laravel eloquent frameworks

我是 Laravel 新手。我正在尝试在两个表之间建立关系。

我的数据库表

评论表

            $table->increments('id');
            $table->text('comment');
            $table->string('shop_name','80');
            $table->bigInteger('product_id');
            $table->timestamps();

comments_images 表

        $table->increments('id');
        $table->bigInteger('comment_id');
        $table->string('images','255');
        $table->string('shop_name','80');
        $table->timestamps();

==========================

评论模型

public function images()
    {
        return $this->hasMany(Comments_images::class,'comment_id');
    }

评论图像模型

public function comments()
    {
        return $this->belongsTo(Comment::class);
    }

我尝试像这样返回相关数据

return Comments_images::find(439)->comments()->get();

return Comment::find(880)->images()->get();


return (new Comment())->images()->get();

它们都不起作用!

我应该做什么?

最佳答案

您是否正确使用了命名空间?例如,“App\Comments_images”。此外,模型最好保持单数形式,例如“Comment”或“Comment_Image”。我提出这个问题是因为你不一致,这可能会导致错误。最后一件事是使用类的字符串,而不是返回实际的类。请参阅下面的示例,并注意大写,并且我没有在某些内容上添加“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');
}

编辑:随意使用 Comment::class 而不是字符串 'App\Comment' - 它解析为相同的内容并且与编辑器导航配合得更好,自动完成和其他有用的东西。

关于php - laravel Eloquent 关系不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46187142/

相关文章:

php session 和 while 循环 : undefined index

如果列的默认 NULL 值更改为某个值,则 MySQL 触发器不会执行

mysql - 向 MySQL 5.5 表添加索引时何时创建 btree?

mysql - 数据透视表省略具有空值的行

javascript - 创建子类别选择框 onChange

symfony2.8 的 php_apcu.dll 扩展推荐 xampp 上的 php 加速器

php - 使用 php 的 HTML 表单无法使用单个提交按钮。

php - 您的要求无法解析为一组可安装的软件包。 - 交响乐项目

php - Laravel 中的填充方法不起作用?

php - laravel seeder 根据数据库中的现有数据在列中分配一个值