gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 06:06:53 24 4
gpt4 key购买 nike

我正在尝试为 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();

契约(Contract)

$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');
}

在我的 Controller 中,我熟悉保存请求的数据

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

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

$user->save();

我在这个项目中的目标是在我的仪表板中显示 iOS 应用程序用户保存的数据(契约(Contract))。例如,用户信息和他们感兴趣的汽车在我的表格中。有人可以帮我在 Controller (而不是 View )中查询什么。或者为这样的项目提供有用的链接。

最佳答案

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了解更多信息。

关于ios - 通过外键 (API) 保存/检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40949327/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com