Laravel Eloquent Relationships - 完整性约束违规

时间:2016-05-01 14:40:15

标签: php mysql eloquent laravel-5.2

我有3个模型:优先级,任务和用户

优先级

  • 可以分配给许多任务
  • 属于一个用户

代码......

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);
    }
}

任务

  • 分配了一个优先级
  • 属于一个用户

代码......

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);
    }
}

用户

  • 可以有很多任务
  • 可以有很多优先事项

代码......

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

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');
    }
}

错误

现在,当我想存储任务时,它会给我以下错误:

  

SQLSTATE [23000]:完整性约束违规:1452无法添加或   更新子行:外键约束失败(taskstasks,   约束tasks_priority_id_foreign外键(priority_id)   参考prioritiesid))(SQL:插入tasksname,   user_idupdated_atcreated_at)值(测试任务,1,   2016-05-01 14:11:21,2016-05-01 14:11:21))

是否可以使用此构造,还是必须在优先级表和任务表之间使用多态关系?

我的表格

数据库模型图片: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');
        });
    }
}

更新

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');
    }
}

2 个答案:

答案 0 :(得分:0)

在您的商店方法中。它说的创建方法:

用户>任务()。该位仅在用户和任务表中插入数据。这就是为什么你有外键错误。由于您没有更新其中一个表(优先级),并且您已经在表中添加了外键,因为我可以从迁移中看到。

如果您有一个名为task_user的数据透视表,其中包含userid,taskid和priority_id,那么您尝试实现的目标是正确的。这将是完美的,因为您只需使用userid和taskid更新优先级列。这是一种方式,但它只需要很少的更改,或者您可以单独将数据插入用户和任务表,您只需要更改查询。你喜欢哪个?我可以告诉你一个你喜欢的例子。

    //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');

请解释视图或显示屏幕截图,您是如何处理它的。现在,我已经为您提供了一个控制器处理优先级和任务的解决方案。

答案 1 :(得分:0)

<强>解

我将priority_id属性添加到任务模型中的可填充数组。

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

我遇到了一个理解问题,因为user_id是从框架中自动分配的,但是在fillable数组中没有指定。那是因为我说$ request-&gt; user-&gt; tasks-&gt; create();它是从框架中分配的,但priority_id是通过用户分配的,因此它是批量分配的,需要在可填充数组中指定。

@Murlidhar Fichadia