数据库与Eloquent laravel

时间:2015-07-29 04:13:44

标签: php laravel eloquent

我正在尝试保存一些复选框的输入。

我有一个表users_cities:

id_user | id_city
--------+---------
   1    |    1
   1    |    2
   2    |    1

我有一个带有三个复选框的视图。

city1 city2 city3,id_user = 1的情况而言,会检查city1和city2。

我要做的是,如果用户选择方框3并取消选中方框2或只选择方框3,则Eloquent会识别并与数据库同步数据。

public function update($id)
{
    $city[] = \App\City::find($id);

    $input = Request::all();

    //Tried:      $city->sync($input)
    //Also tried: $city->delete(); $city->save($input);
    return redirect()->back();
}

id_user变量上的$city$input上的城市有@extends('welcome') @section('content') <h1>Atualizar cidades</h1> @foreach ($city as $citySelect) <?php $number[] = $citySelect->id_city; ?> @endforeach {!! Form::model($city, ['route' => ['cities.update', $citySelect->id_user]]) !!} @foreach ($cidades as $cidadesnome) {!! Form::checkbox($cidadesnome->id, $cidadesnome->name, (in_array($cidadesnome->id, $number)), ['class' => 'field']) !!}{!! $cidadesnome->name !!} @endforeach <button class="btn btn-success" type="submit"> Atualizar Cidades </button> {!! Form::close() !!} @stop 但是我无法使其发挥作用。

查看:

public function cities() {
    return $this->belongsToMany('City', 'users_cities', 'id_city', 'id_user');
}

public function users() {
    return $this->belongsToMany('Users', 'users_cities', 'id_user', 'id_city');
}

关系:

;WITH cte AS
(
   SELECT *, ROW_NUMBER() OVER (PARTITION BY pe.removed_date ORDER BY e.removed_date DESC) AS rn
   FROM person p inner join placement_episode pe on p.person_id = pe.child_id

)
SELECT *
FROM cte
WHERE rn = 1 

1 个答案:

答案 0 :(得分:0)

  

id_user变量上的$city$input上的城市,但我无法使用此功能。

由于您使用$city[] = \App\City::find($id);因此$city不是id_user,而是包含App\City的一个实例的数组,因此无法生成。

为了同步ID为$id的用户的城市,您需要执行的操作是:

public function update($id)
{
    $user = \App\User::findOrFail($id);
    $input = Request::all();
    $user->cities()->sync($input['cities']);

    return redirect()->back();
}

您还需要更改复选框名称以发送一系列城市,并使用名称cities[]

@foreach ($cidades as $cidadesnome)
    <label>
    {!! Form::checkbox('cities[]', $cidadesnome->id, (in_array($cidadesnome->id, $number)), ['class' => 'field']) !!}{!! $cidadesnome->name !!}
    </label>
@endforeach

假设您在模型中定义了正确的关系。我发现您没有关注Eloquent naming convention列名称。我强烈建议你关注他们。它们将使您的关系定义更加容易。