mysql - Laravel 5 创建属于 3 个其他表的新记录

标签 mysql laravel eloquent laravel-5 laravel-5.1

我有 4 个表 Users、Regions、Rentals 和 Locations

  1. 每个用户都有很多出租
  2. 每个地区都有很多出租
  3. 每个位置都有很多出租
  4. 基本上一个 Rental 属于所有 3 个表

地区 - id, name 位置 - ID、街道地址、城市、省份、邮政编码 出租 - id, region_id, location_id, user_id

我已经在这些表之间设置了 hasMany 和 belongsTo 关系并在 Tinker 中测试了它们,但现在我想创建和更新租金。

  • region_id 通过请求向上传递 - $regionId
  • user_id 是 Auth::id() - $userId
  • location_id 是通过请求的 only() 部分并检查位置表找到的,如果它存在,我会获取 location_id - $locationId
  • 再次使用 only() 获取剩余的发布数据 - $rentalData

到目前为止所有这些都有效,但是您如何使用我提取的 ID 和数据创建和更新租金,这几乎有效:

Location::find($locationId)->rentals()->create($rentalData);

但是,需要以某种方式将 $locationId 和 $userId 混合在一起,让它们可填充似乎并不正确。

到目前为止我一直这样玩:

// Retrieve the chosen rental region
$regionId = Region::find($request->input('region_id'));

// Retrieve authenticated user id
$userId = Auth::id();

// Retrieve rental location data
$rentalLocationData = $request->only('street_address', 'city', 'province', 'country', 'postal_code');

// Does the location already exist? If not create and persist it to the database
$locationData = RentalLocation::firstOrCreate($rentalLocationData);
$locationId = $locationData->id;

// Create the rental...?
$rental = Location::find($locationId)->rentals()->create($rentalData);

更新

所以我可以继续使用 ORM 并这样做,但我仍然想了解 Eloquent 是如何工作的,而不是我在观看 Laracast 视频时学到的基础知识,所以任何帮助将不胜感激,现在我只是觉得它真的很困惑:

// Retrieve rental location data from the request
$requestData = $request->only('street_address', 'city', 'province', 'country', 'postal_code');

// Does the location already exist? If not create and persist it to the database
$rentalLocation = RentalLocation::firstOrCreate($requestData);


// Retrieve the foreign key ids not included in request
$foreignKeyIds = [ 'user_id' => Auth::id(), 'rental_location_id' => $rentalLocation->id ];

// Retrieve request data for creating a rental, and merge with foreign key ids
$requestData = $request->only('region_id', 'stall', 'level', 'description');
$rentalData = array_merge($foreignKeyIds, $requestData);

// Insert new rental with all field attributes included
DB::table('rentals')->insert($rentalData);

更新

这个解决方案怎么样?

RentalRequest 检查 region_id 是否存在,用户将始终是 Auth::user()。

public function store(RentalRequest $request)
{
    // Retrieve the authenticated user
    $User = Auth::user();

    // Retrieve rental location data from request
    $requestData = $request->only('street_address', 'city', 'province', 'country', 'postal_code');

    // Does the location already exist? If not create and persist it to the database
    $RentalLocation = RentalLocation::firstOrCreate($requestData);

    // Retrieve the region for inserting the rental
    $Region = Region::find($request->input('region_id'));

    // Retrieve rental data from request
    $requestData = $request->only('stall', 'level', 'description');

    // Create a new rental, fill with request data, and add relationships
    $rental = new Rental;
    $rental->fill($requestData);
    $rental->owner()->associate($User);
    $rental->location()->associate($RentalLocation);

    // Persist rental to database
    $rental = $Region->rentals()->save($rental);

    // Return rental data for capture by AngularJS interceptor
    // TODO: filter rental data don't need it all returned to client
    return response()->json([
        'rental' => $rental,
        'action' => 'rental_registered',
        'message' => trans('rental.registered')
    ]);
}

最佳答案

我不明白为什么要把它搞得这么复杂?

试试这个:

解决方案一

$User = User::find(Auth::id()); 
if(!$User) {
    return 'no user';
}

$Region = Region::find($request->input('region_id'));
if(!$Region) {
    return 'no region';
}

$locationData = $request->only('street_address', 'city', 'province', 'country', 'postal_code');
$Location = Location::firstOrCreate($locationData);

$rentalData = [
    'user_id' => $User->id, 
    'region_id' => $Region->id, 
    'location_id' => $Location->id
];
$Rental = Rental::firstOrCreate($rentalData);

方案二

// ->remember() for caching request to prevent many queries, for faster result use apc cache in config files, no need to use memcache when You're using 1 app server

if(!User::where('id', '=', Auth::id())->remember(1440)->exists()) {
    return 'no user';
}

if(!Region::where('id', '=', $request->input('region_id'))->remember(1440)->exists()) {
    return 'no user';
}

$locationData = $request->only('street_address', 'city', 'province', 'country', 'postal_code');
$Location = Location::firstOrCreate($locationData);

$rentalData = [
    'user_id' => $User->id, 
    'region_id' => $Region->id, 
    'location_id' => $Location->id
];
$Rental = Rental::firstOrCreate($rentalData);

关于mysql - Laravel 5 创建属于 3 个其他表的新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31442013/

相关文章:

MySQL 截断错误

php - 使用 php 延迟发送电子邮件

mysql - 如果用户是笔记的所有者,如何选择?数据库管理系统

javascript - Laravel jQuery 自动完成速度

php - 用于 rest api 的 laravel 表单请求验证消息

php - 将 SQL 查询更改为 Eloquent 查询

mysql - AVG/COUNT MySQL 查询不起作用

php - Laravel - POST 方法重定向到表单,刷新它并显示 "required error"

php - Laravel:Order By hasMany 关系的第一个(最旧的)条目

mysql - Laravel HasManyThrough,访问主要/次要用户推荐