我有错误,而且我不知道如何正确使用雄辩的关系: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
});
以下是DB模型:
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'];
}
Controller ModelsController
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
,CONSTRAINTmodel_photosets_model_id_foreign
FOREIGN KEY(model_id
)参考models
(user_id
)ON DELETE CASCADE)(SQL:insert intomodel_photosets
(category_id
,model_id
)值(2,2))
答案 0 :(得分:0)
错误显示您正在尝试使用model_id 2插入到model_photosets中,但是在ID为2的模型中的记录不会退出。