首页 文章

将数据透视表附加到laravel中的其他两个表

提问于
浏览
0

我有2张 table . 一个是用户,一个是位置 . 我创建了一个名为user_locations的数据透视表 . 用户可以拥有一个或多个位置 . 位置可以属于一个或多个用户 . 所以我在这些 table 上有很多关系 . 我已经阅读了laravel中的attach方法,但我不太确定如何使用它 .

在我的用户和位置表中,我有一个id,它都进入我的数据透视表user_id和location_id .

$user = new User;
$user->organisation_id = Auth::user()->organisation_id;
$user->fill(Input::except('locations'));

$input_locations = Input::only('locations');

foreach($input_locations as $input_location){
$location_id = Location::where('name', '=', $input_location)->get();
$location = Location::find($location_id);

$user->User_location()->associate($location);

在这个时刻,我遇到了两个问题 . 在Location :: where('name ...我应该从$ input_locations检查id但我不知道如何获取id?有一个id和一个名字来自Input :: only('locations') .

我的第二个问题是最后一行代码 . 在这里我应该使用附加 . 我在laravel docs中找到了这个:

您还可以传递一组属性,这些属性应存储在数据透视表中以用于关系:

$user->roles()->attach(1, array('expires' => $expires));

所以我认为它应该是这样的:

$user->user_locations()->attach(the new user id, array('location_id' => $location_id));

真的希望有人可以帮助我,因为我真的不知道从这里开始 .

UPDATE:

这是我的用户控制器:

public function createUserPost()
{
    $user = new User;
    $user->organisation_id = Auth::user()->organisation_id;
    $user->fill(Input::except('locations'));

    // pak het field locations
    $input_locations = Input::only('locations');

    if($user->save())
    {
        // Koppel de id's van de locatie aan de nieuwe user
        $new_user_id = $user->id;
        foreach ($input_locations as $key => $value) {
            $location = Location::find($value);
            User::find($new_user_id)->locations()->attach($location);
        }
        return Redirect::to('users/'.$user->id);
    }
    return $this->createUser($user);
}

在我的用户模型中,我有这样的规则:

'locations' => 'required',

这是必需的,因为它是必填字段 . 现在,当我点击提交按钮时,它不会保存用户,但是说填充时需要字段“位置” . 问题是选择的名称是位置 . 但我不知道怎么把它放到我的 table 里,因为我没有一个叫做位置的专栏 . 只需填写我的数据透视表并确保表单中需要该字段 .

1 回答

  • 0

    你为什么不用Laravel's Relations

    你想要一个多对多的关系 . 在这种情况下,将数据透视表重命名为 location_user (默认情况下,它应该是按字母顺序排列的) .

    然后定义你的关系:

    // In User.php model
    protected $fillable = ['first_name', 'last_name']; \\ List of all allowable items to be filled
    
    public function locations()
    {
        return $this->hasMany('Location');
    }
    
    // In Location.php model
    public function users()
    {
        return $this->hasMany('User');
    }
    

    之后,有很多方法可以将 Location 附加到 User . 最好的方法是:

    public function createUserPost()
    {
        $user = new User(Input::all); // Use the $fillable in the model to allow mass assign
    
        // This should be done via a relationship
        $user->organisation_id = Auth::user()->organisation_id;
    
        // pak het field locations
        $input_locations = Input::only('locations');
    
        $location_ids = [];
        foreach($input_locations as $key => $id) {
            $location_ids[] = Location::find($value)->id;
        }
        $user->locations()->attach($location_ids);
    
        if($user->save())
        ...
    }
    

相关问题