【问题标题】:Laravel belongsTo relationship not workingLaravel 属于关系不起作用
【发布时间】:2017-11-01 14:18:22
【问题描述】:

我有三个模型,我创建了帖子和评论以及用户。我正在尝试在两者之间建立关系。评论和发布它们都有一个与用户表上的 id 匹配的字段“user_id”。以下是我要设置的关系:

comment.php:

<?php

namespace App;


class Comment extends Model
{
    //
    public function post(){

        return $this->belongsTo(Post::class);
    }



    public function user(){ 

        return $this->belongsTo(User::class);
    }
}

Post.php:

<?php

namespace App;

class Post extends Model
{

    public function comments(){

        return $this->hasMany(Comment::class);
    }

    public function addComment($body, $name, $email){




        $this->comments()->create(compact('body','name','email'));
    }

       public function user(){ // $comment->user->name

        return $this->belongsTo(User::class);
    }
}

用户.php

    <?php

namespace App;
use App\Post;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function post(){

        return $this->hasMany(Post::class);
    }



}

现在您可以看到评论属于用户,帖子属于用户。

但是,当我尝试通过 tinker 创建新帖子时(没有在数据库上创建用户或登录用户),我可以毫无问题地创建帖子;

这告诉我,帖子必须有用户和评论也必须有用户的关系不起作用!知道如何解决这个问题吗?

迁移:

create_posts_migration:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->string('title');
            $table->text('body');
            $table->string('image');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

create_comment_migration:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCommentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('post_id');
            $table->integer('user_id');
            $table->string('email');
            $table->string('name');
            $table->string('body');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('comments');
    }
}

【问题讨论】:

  • 请出示您的 User.php 文件。
  • 我编辑了帖子,所以现在就在那儿
  • 检查您是否在“posts”表中添加了“user_id”列。
  • 是的,它就在那里!已检查。
  • 仅仅因为你有一个user_id 字段并不意味着它会自动强制关系。您需要在迁移中添加外键约束以强制使用有效用户设置该字段。分享您的迁移。

标签: php database laravel eloquent


【解决方案1】:

在您的迁移中添加外键约束以在创建帖子时检查有效用户,并在创建 cmets 时检查有效用户和帖子。这应该可以解决您的问题。

Schema::create('posts', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('user_id');
    $table->string('title');
    $table->text('body');
    $table->string('image');
    $table->timestamps();

    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

Schema::create('comments', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('post_id');
    $table->unsignedInteger('user_id');
    $table->string('email');
    $table->string('name');
    $table->string('body');
    $table->timestamps();

    $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

根据您的需要更改onDelete 选项。 cascade 将在删除父级时删除子级关系。

【讨论】:

  • SQLSTATE[23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败
  • @L.Kelmendi 这不是您帖子的重点吗?它按预期工作。您现在必须在创建帖子时设置有效用户,在创建评论时设置有效帖子和用户。您在模型中设置的关系用于在您使用 eloquent 创建外键时适当地获取和分配外键。
  • 是的;我的重点是吹一个错误。但是,我继续为用户制作了注册/登录表格。所以我登录并很高兴创建帖子,但它正在炸毁相同的错误 sqlstate[23000]
  • @L.Kelmendi 您需要在创建帖子时分配 user_id。或者以雄辩的方式进行,并在创建时附加用户发布。这是你手头的另一个问题。如果您不知道如何操作,请查看文档或使用您的控制器代码创建一个新问题以创建帖子或 cmets。我会告诉你如何解决它。
  • 是的,我也解决了这个问题: Post::create([ 'title'=>request('title'), 'body' =>request('body'), 'user_id'= >auth()->id(), 'image' =>$destination.'/'.$filename ]);
猜你喜欢
  • 2018-01-10
  • 1970-01-01
  • 2015-09-24
  • 1970-01-01
  • 2017-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多