简体   繁体   English

Laravel雄辩的关系-违反完整性约束

[英]Laravel Eloquent Relationships - Integrity constraint violation

I have 3 models: Priority, Task and User 我有3个模型:优先级,任务和用户

Priority 优先

  • can be assigned to many tasks 可以分配给许多任务
  • belongs to one user 属于一个用户

Code ... 代码...

class Priority extends Model
{
    protected $fillable = ['name', 'hexcolorcode'];

    protected $casts = [
        'user_id' => 'int',
    ];

    public function task()
    {
        return $this->hasMany(Task::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Task 任务

  • has one priority assigned 分配了一个优先级
  • belongs to one user 属于一个用户

Code ... 代码...

class Task extends Model
{
    protected $fillable = ['name'];

    protected $casts = [
        'user_id' => 'int',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function priority()
    {
        return $this->hasOne(Priority::class);
    }
}

User 用户

  • can have many tasks 可以有很多任务
  • can have many priorities 可以有很多优先事项

Code ... 代码...

class User extends Authenticatable
{

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function tasks()
    {
        return $this->hasMany(Task::class);
    }

    public function priorities()
    {
        return $this->hasMany(Priority::class);
    }
}

TaskController TaskController

class TaskController extends Controller
{
    protected $tasks;

    private $priorities;

    public function __construct(TaskRepository $tasks, PriorityRepository $priorities)
    {
        $this->middleware('auth');
        $this->tasks = $tasks;
        $this->priorities = $priorities;
    }

    public function index(Request $request)
    {
        return view('tasks.index', [
            'tasks' => $this->tasks->forUser($request->user()),
            'priorities' => $this->priorities->forUser($request->user())
        ]);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|max:255',
            'description' => 'required',
            'priority' => 'required'
        ]);

        $request->user()->tasks()->create([
            'name' => $request->name,
            'description' => $request->description,
            'priority_id' => $request->priority
        ]);

        return redirect('/tasks');
    }

    public function edit(Task $task)
    {
        $this->authorize('edit', $task);

        return view('tasks.edit', compact('task'));
    }

    public function update(Request $request, Task $task)
    {
        $this->validate($request, [
            'name' => 'required|max:255',
        ]);

        $task->update($request->all());
        return redirect('/tasks');
    }

    public function destroy(Request $request, Task $task)
    {
        $this->authorize('destroy', $task);

        $task->delete();

        return redirect('/tasks');
    }
}

Error 错误

Now when I want to store a task it gives me following error: 现在,当我想存储任务时,它给了我以下错误:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ( tasks . tasks , CONSTRAINT tasks_priority_id_foreign FOREIGN KEY ( priority_id ) REFERENCES priorities ( id )) (SQL: insert into tasks ( name , user_id , updated_at , created_at ) values (test task, 1, 2016-05-01 14:11:21, 2016-05-01 14:11:21)) SQLSTATE [23000]:违反完整性约束:1452无法添加或更新子行:外键约束失败( taskstasks ,CONSTRAINT tasks_priority_id_foreign FOREIGN KEY( priority_id )参考prioritiesid ))(SQL:插入tasksnameuser_idupdated_atcreated_at )值(测试任务,2016年1月1日,2016-05-01 14:11:21,2016-05-01 14:11:21))

Is it possible with this construct or do I have to use Polymorphic Relations between priority table and tasks table? 这种结构是否可能,或者我必须在优先级表和任务表之间使用多态关系?

My Tables 我的桌子

Database Model Picture: http://picpaste.de/mysql-kBH4tO5T.PNG 数据库模型图片: http : //picpaste.de/mysql-kBH4tO5T.PNG

class CreatePrioritiesTable extends Migration
{

    public function up()
    {
        Schema::create('priorities', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->char('name');
            $table->char('hexcolorcode', 7);
            $table->timestamps();
            $table->foreign('user_id')->references('id')->on('users');
        });
    }
}


class CreateTasksTable extends Migration
{

    public function up()
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('name');
            $table->text('description');
            $table->integer('priority_id')->unsigned();
            $table->timestamps();
            $table->foreign('priority_id')->references('id')->on('priorities');
            $table->foreign('user_id')->references('id')->on('users');
        });
    }
}

UPDATE 更新

PriorityController 优先控制器

class PriorityController extends Controller
{

    protected $priorities;

    public function __construct(PriorityRepository $priorities)
    {
        $this->middleware('auth');
        $this->priorities = $priorities;
    }

    public function index(Request $request)
    {
        return view('priority.index', [
            'priorities' => $this->priorities->forUser($request->user()),
        ]);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|max:255',
            'hexcolorcode' => 'required|max:7'
        ]);

        $request->user()->priorities()->create($request->all());

        return redirect('/priorities');
    }

    public function edit(Priority $priority)
    {
        $this->authorize('edit', $priority);

        return view('priority.edit', compact('priority'));
    }

    public function update(Request $request, Priority $priority)
    {
        $this->validate($request, [
            'name' => 'required|max:255',
            'hexcolorcode' => 'required|max:7'
        ]);

        $priority->update($request->all());
        return redirect('/priorities');
    }

    public function destroy(Request $request, Priority $priority)
    {
        $this->authorize('destroy', $priority);

        $priority->delete();

        return redirect('/priorities');
    }
}

In your store method. 在您的存储方法中。 The create method it says : 它说的创建方法:

user->tasks(). user-> tasks()。 This bit will only inserting data in user and tasks table. 该位将仅在用户和任务表中插入数据。 Thats why you have foreign key error. 这就是为什么您有外键错误。 As you are not updating one of your tables(priority) and also you have added foreign keys in tables as i csn see from migration. 由于您不更新其中一个表(优先级),而且还向表中添加了外键,如我从迁移中看到的那样。

What you are trying to achieve is right if you had a pivot table called task_user where you had userid, taskid and a priority_id. 如果您有一个名为task_user的数据透视表,其中有userid,taskid和priority_id,那么您要实现的目标是正确的。 That would be perfect as you would simply update the priority column with userid and taskid. 这将是完美的,因为您只需使用userid和taskid更新优先级列即可。 Thats one way but it will require few changes OR you can insert data into user and tasks table seperately for which you will need to just change the query. 那是一种方法,但是它几乎不需要更改,或者您可以将数据分别插入到用户表和任务表中,而您只需要更改查询即可。 What do you prefer? 你喜欢哪个? I can show you an example for which you like. 我可以给你看一个你喜欢的例子。

    //for Priority
        // store
        $priorities = new Priority;
        $priorities->name       = Input::get('priority_name');
        $priorities->hexcolorcode      = Input::get('hexcolorcode');
        $priorities->save();

        $priority = Priority::select('id')->orderBy('created_at', 'desc')->first();

    //for Task
    $tasks = new Task;
        $tasks->name       = Input::get('task_name');
        $tasks->priority_id      = Input::get('priority');
        $priorities->save();

        // redirect
        return Redirect::to('some view please change this');

Please explain views or show screenshots, how are you handling it. 请说明视图或显示屏幕截图,您将如何处理它。 For now, I have given you the solution with one controller handling priorities and tasks. 现在,我已经为您提供了一种解决方案,其中包含一个控制器来处理优先级和任务。

SOLUTION

I added the priority_id attribute to the fillable array inside the task model. 我将task_id属性添加到任务模型内部的可填充数组中。

protected $fillable = ['name', 'description', 'priority_id'];

I had an understanding problem, because user_id is assigned automatically from the framework, but it isn't specified in fillable array. 我有一个理解问题,因为user_id是从框架自动分配的,但未在可填充数组中指定。 That's because I say $request->user->tasks->create(); 那是因为我说$ request-> user-> tasks-> create(); it is assigned from the framework, but priority_id is assigned through the user, so it is mass assigned and need to be specified in the fillable array. 它是从框架分配的,但是priority_id是通过用户分配的,因此它是批量分配的,需要在可填充数组中指定。

@Murlidhar Fichadia @Murlidhar Fichadia

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

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