我有錯誤,並且我不知道如何正確使用Eloquent關係:c 類別編號採取正確,但用戶標識爲錯誤。我認爲這是從表models
。 id
,但需要models
。 user_id
這裏是我的表:無法添加或更新子行:外鍵約束失敗(Laravel)
photoset_categories(目錄同photoset類型,例如: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'];
}
控制器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]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (
delavour
.model_photosets
, CONSTRAINTmodel_photosets_model_id_foreign
FOREIGN KEY (model_id
) REFERENCESmodels
(user_id
) ON DELETE CASCADE) (SQL: insert intomodel_photosets
(category_id
,model_id
) values (2, 2))
我知道。 「2」 - 模型表中的字段「id」。但我需要獲取字段'user_id':c 屏幕截圖: https://drive.google.com/open?id=0B8BExJ-ydlwLUVVBM3BkYk5LOFk – MyZik