請問這樣的關聯性要如何使用Eloquent
我在Program Model底下是這樣做的
class Program extends Model {
......
public function operations() {
return $this->belongsToMany(Operation::class, config('permission.table_names')['permissions'], 'operation_id', 'program_id')
->withTimestamps();
}
}
在Operation Model 底下是這樣做的
class Operation extends Model {
......
public function programs() {
return $this->belongsToMany(Program::class, config('permission.table_names')['permissions'], 'operation_id', 'program_id')
->withTimestamps();
}
}
在OperationController裡這樣做
public function store(Request $request) {
$this->validate($request, [
'opr_id'=>'required|max:120|unique:operations',
'desc'=>'required|max:120'
]);
$opr_id = $request['opr_id'];
$operation = new Operation();
$operation->opr_id = $opr_id;
$operation->desc = $request['desc'];
$operation->save();
$programs = $request['programs'];
$operation = Operation::where('opr_id', '=', $opr_id)->first();
if(is_array($programs)) {
$operation->programs()->sync([1]);
} else {
$operation->programs()->detach();
}
return redirect()->route('operations.index')
->with('flash_message',trans('messages.operation_successfully_added',['name'=> $opr_id]));
}
public function update(Request $request, $id) {
$operation = Operation::findOrFail($id);
$this->validate($request, [
'opr_id'=>'required|max:120',
'desc'=>'required|max:120'
]);
$input = $request->only('opr_id','desc');
$operation->fill($input)->save();
$programs = $request['programs'];
$programs = array_map('intval', $programs);
$operation->programs()->detach();
if(is_array($programs)) {
$operation->programs()->sync($programs);
}
return redirect()->route('operations.index')
->with('flash_message',trans('messages.operation_successfully_updated',['name'=> $input['opr_id']]));
}
store 成功的新增了permissions,但是update時卻是沒有變化的,不知問題出在哪兒
是否是因為foreign key的關係而無法正常運作?我又該如何修改?
第一次提問+剛學習laravel,若有敘述不清的部分,請多包涵
通常 update 如下:
$flight = App\Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();
你要確定資料 find 是否找到要更新的那一筆,另外,就是資料是否有正確改變。
$operation->fill($input)->save();
寫法是否OK,我就不確定了。
謝謝您的回答,但我在update operation的時候沒有問題的
但是在
$operation->programs()->detach();
if(is_array($programs)) {
$operation->programs()->sync($programs);
}
這部分是沒辦法正常同步關聯的。
我都是使用 attach,attach與sync 差別如下:
https://stackoverflow.com/questions/23968415/laravel-eloquent-attach-vs-sync
謝謝您的回答,
因為我每次都需要將關聯刪除,所以我有加入
$operation->programs()->detach();
但是他並沒有刪除關聯
我想是否是因為我將樞紐表(permissions)加入了id,導致於detach() not working