通过外键(API)保存/检索数据

时间:2016-12-03 15:23:40

标签: ios mysql laravel orm eloquent

我正在尝试为iOS应用设置我的API。这是我第一次使用Laravel作为API,所以这就是我在表格中的内容:

汽车

Schema::create('cars', function (Blueprint $table) {
        $table->increments('id');

        $table->string('name')->nullable();
        $table->string('age')->nullable();
        $table->string('model')->nullable();
        $table->string('color')->nullable();

用户

        $table->increments('id');
        $table->string('name')->nullable();
        $table->string('street')->nullable();
        $table->string('niehgborhood')->nullable();
        $table->string('city')->nullable();

合同

$table->increments('id');

        $table->integer('user_id')->unsigned;
        $table->foreign('user_id')->references('id')->on('users');

        $table->integer('car_id')->unsigned;
        $table->foreign('car_id')->references('id')->on('cars');

模型

protected $table = 'users';

protected $guarded = ['id'];
protected $fillable = ['phone', 'email',
    'street','city','niehgborhood'
    ,'national_id'];

public function cars()
{
    return $this->hasMany('App\User');
}

用户

 protected $guarded = ['id'];

protected $fillable = ['name', 'age',
     'color, model'
    ];


public function users()
{
    return $this->belongsToMany('App\Cars');
}

在我的控制器中我熟悉保存请求的数据

$user = JWTAuth::parseToken()->authenticate();

    $user->phone = $request->phone;
    $user->city = $request->city;

    $user->save();

此项目的目标是在我的信息中心中显示iOS应用用户保存的数据(合同)。例如,用户信息和他们对我的桌子感兴趣的汽车。有人可以帮助我在控制器(而不是视图)中进行查询。或者为这样的项目提供有用的链接。

1 个答案:

答案 0 :(得分:2)

UserCars之间的关系应为many-to-many。请阅读文档以正确应用此关系。

如果您的关系在那里,那么您可以这样做:

$user = JWTAuth::parseToken()->authenticate();

$cars = $user->cars; // returns collection of cars associated with the user.

例如 - 在User模型中定义以下关系:

public function cars()
{
    return $this->belongsToMany('App\Car');
}

<强>更新

要保存用户和关联汽车,您可以按照以下步骤进行操作:

$user = JWTAuth::parseToken()->authenticate();

$user->phone = $request->phone;
$user->city = $request->city;

$user->save();

$car_ids = $request->car_ids; // it should return an array

$user->cars()->sync($car_ids);

存储数据的方法有很多种。有关详细信息,请阅读文档here

相关问题