【发布时间】:2017-09-14 16:24:02
【问题描述】:
我有错误,我不知道如何正确处理 Eloquent 关系:c
类别编号正确,但用户ID错误。我认为它取自表格models.id,但需要models.user_id
这是我的表格:
photoset_categories(包含照片集类型的目录,例如: id = 1, name = 'Studio'; id = 2, name = 'Portrait')
Schema::create('photoset_categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->comment('Category name');
});
模型(模型数据:眼睛颜色、身高、体重等)
Schema::create('models', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->comment('Model id from users');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); // Foreign key
$table->timestamps();
});
model_photosets(模特被拍到的照片)
Schema::create('model_photosets', function (Blueprint $table) {
$table->increments('id');
$table->integer('model_id')->unsigned()->index();
$table->foreign('model_id')->references('user_id')->on('models')->onDelete('cascade'); // Foreign key
$table->integer('category_id')->unsigned()->index();
$table->foreign('category_id')->references('id')->on('photoset_categories')->onDelete('cascade'); // Foreign key
});
这里是数据库模型:
class PhotosetCategory extends Model
{
protected $table = 'photoset_categories';
protected $guarded = ['name'];
public function modelPhotoset()
{
return $this->belongsToMany('App\Models');
}
}
...
class Models extends Model
{
protected $table = 'models';
protected $fillable = ['user_id', 'd_birth', 'birth', 'm_birth', 'y_birth', 'hair_color', 'eyes_color', 'growth', 'weight'];
protected $dates = ['created_at', 'updated_at'];
public function user() {
return $this->belongsToMany('App\User');
}
public function photosets()
{
return $this->belongsToMany('App\PhotosetCategory', 'model_photosets', 'model_id', 'category_id');
}
}
...
class ModelPhotoset extends Model
{
protected $table = 'model_photosets';
protected $fillable = ['user_id', 'category_id'];
}
控制器模型控制器
class ModelsController extends Controller
{
public function editData(Request $request)
{
$title = 'Model data';
$data = Models::where('user_id', Auth::id())->first();
$all_types = PhotosetCategory::all(); // List of photo shoot catagories
if ($request->has('save')) {
$this->validate($request, [
// ...
]);
// UPDATE USER PRO SHOOTS DATA
$data->photosets()->sync($request->get('ps_types'));
}
return view('model.edit', [
'title' => $title,
'data' => $data,
]);
}
}
错误:
SQLSTATE[23000]:违反完整性约束:1452 无法添加或 更新子行:外键约束失败 (
delavour.model_photosets, 约束model_photosets_model_id_foreign外键 (model_id) 参考models(user_id) ON DELETE CASCADE) (SQL: 插入model_photosets(category_id,model_id) 值 (2, 2))
【问题讨论】:
标签: mysql laravel eloquent foreign-keys migration