dstew32424 2015-06-16 13:44
浏览 57
已采纳

将元素同步到Laravel上的孩子

My Shema database is

User Table

    id
    login
    parent

Sign Table

    id
    name
    user_id (Sign owner)

Pivot table user_sign

    id
    user_id
    sign_id

My User model contain

    public function signs() {
        return $this->belongsToMany('App\Sign', 'user_sign');
    }


    public function parent(){
        return $this->belongsTo('User', 'parent');
    }

    public function children(){
        return $this->hasMany('User', 'parent', 'user_id');
    }

And my Sign model contain

    public function users() {
        return $this->belongsToMany('App\User', 'user_sign')->select(['users.id','name']);
    }

A parent user can attach / sync Sign to a child user via this route (he send sign_id and child_id)

    Route::put('sign/share', 'SignController@share')

To do this action, in my controller i must check : - if Owner of sign_id is $user_id - If child_id is child of $user_id

And after that, i do my attach / sync.

Now, in my controller i have :

public function share(Request $request)
{
    $userId = $request->input('user_id');
    $sign = Sign::where('user_id', $userId)->find($id);

    if(!$sign){
        return response()->json(['message'=>'FAIL'], 404);
    }
}

But I completely blocked after this... It's possible to check and attach in one line ?

Thanks for your help

  • 写回答

1条回答 默认 最新

  • doumeng1089 2015-06-16 13:58
    关注

    As far as syncing/attaching you can use this sytanx

    $user->roles()->sync([1, 2, 3]);
    

    As given in Laravel Docs

    You can do the both checks in the condition of IF and assign in case of true, thats how your controller will look like finally.

        public function share(Request $request)
        {
            $userId = $request->input('user_id');
            $signId = $request->input('sign_id');
            $childId = $request->input('child_id');            
            if (Sign::find($singId)->user_id == $userId && User::find($userId)->child_id == $childId) 
            {
    
               //Attach the sign to child user
               User::find($childId)->signs()->attach($signId);
    
            }
            else 
            {
    
                  return response()->json(['message'=>'FAIL'], 404);
    
            }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题