Laravel 5创建属于3个其他表的新记录 [英] Laravel 5 Creating a New Record that BelongsTo 3 Other Tables
问题描述
我有4张表用户,地区,租借和地点
- 每个用户都有多个租借
- 每个位置都有多个租借
- 基本上租赁属于所有3个表
<每个地区都有多个租赁
区域 - id,名称
位置 - id,street_address,city,province,postal_code
租赁 - id,region_id,location_id,user_id
我已经设置了这些表之间的hasMany和belongsTo关系,并在Tinker中进行了测试,但现在我想创建和更新租赁。
- region_id通过请求传递 - $ regionId
- user_id是Auth :: id() - $ userId
- 通过仅获取()部分请求并对位置表进行检查,找到location_id,如果存在,我抓住location_id - $ locationId
- 剩下的帖子数据被抓住g only()再次为该数据 - $ rentalData
所有这一切都适用于这一点,但是如何您使用我提取的ids和数据创建和更新租赁,这几乎可以工作:
Location :: find($ locationId) - >出租() - >创建($ rentalData);
但是,需要将$ locationId和$ userId转换成混合,而且似乎不有权让他们可以填充。
我一直在玩这样的东西:
//获取所选租赁区域
$ regionId = Region :: find($ request-> input('region_id'));
//检索经过身份验证的用户ID
$ userId = Auth :: id();
//检索出租位置数据
$ rentalLocationData = $ request-> only('street_address','city','province','country','postal_code');
//位置是否已经存在?如果不创建并持久到数据库
$ locationData = RentalLocation :: firstOrCreate($ rentalLocationData);
$ locationId = $ locationData-> id;
//创建租赁...?
$ rental = Location :: find($ locationId) - > rental() - > create($ rentalData);
更新
所以我可以继续下去使用ORM,并做到这一点,但我仍然希望了解如何卓越的工作超出了基础知识,我学会了观看拉拉斯卡夫视频,所以任何帮助将不胜感激,现在我只是发现它真的令人困惑:
//从请求中获取租金位置数据
$ requestData = $ request-> only('street_address' ,城市,省,国家,邮政编码);
//位置是否已经存在?如果没有创建并保存到数据库
$ rentalLocation = RentalLocation :: firstOrCreate($ requestData);
//检索未包含在请求中的外键ID
$ foreignKeyIds = ['user_id'=> Auth :: id(),'rental_location_id'=> $ rentalLocation-> id];
//检索创建出租的请求数据,并与外键ID相结合
$ requestData = $ request-> only('region_id','stall','level' '描述');
$ rentalData = array_merge($ foreignKeyIds,$ requestData);
//插入包含所有字段属性的新租赁
DB :: table('rental') - > insert($ rentalData);
更新
这个解决方案呢?
RentalRequest检查region_id是否存在,用户永远是Auth :: user()。
public function store(RentalRequest $ request)
{
//检索经过身份验证的用户
$ User = Auth :: user ();
//从请求中获取租金位置数据
$ requestData = $ request-> only('street_address','city','province','country','postal_code') ;
//位置是否已经存在?如果不创建并持久到数据库
$ RentalLocation = RentalLocation :: firstOrCreate($ requestData);
//检索用于插入租金的区域
$ Region = Region :: find($ request-> input('region_id'));
//从请求中获取租用数据
$ requestData = $ request-> only('stall','level','description');
//创建一个新租金,填写请求数据,并添加关系
$ rental = new租赁;
$ rental-> fill($ requestData);
$ rental-> owner() - > associate($ User);
$ rental-> location() - > associate($ RentalLocation);
//持续租赁到数据库
$ rental = $ Region-> rental() - > save($ rental);
//返回由AngularJS拦截器捕获的租用数据
// TODO:过滤器租用数据不需要全部返回给客户端
return response() - > json ([
'rental'=> $ rental,
'action'=>'rental_registered',
'message'=> trans('rental.registered')
]);
}
我不明白为什么这样做很复杂?
尝试这个:
解决方案1 p>
$ 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);
解决方案2
对于缓存请求来说,记住()缓存请求以避免许多查询,为了更快的结果,使用配置文件中的apc缓存,当您使用1个应用程序时,不需要使用memcache服务器
if(!User :: where('id','=',Auth :: id()) - >记住(1440) - > exists()){
return'no user';
}
if(!Region :: where('id','=',$ request-> input('region_id'))>记住(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);
I have 4 tables Users, Regions, Rentals, and Locations
- Each User hasMany Rentals
- Each Region hasMany Rentals
- Each Location hasMany Rentals
- Basically a Rental belongsTo all 3 tables
Region - id, name Location - id, street_address, city, province, postal_code Rental - id, region_id, location_id, user_id
I've set up the hasMany and belongsTo relationships between these tables and tested them in Tinker, but now I want to create and update rentals.
- The region_id is passed up through the request - $regionId
- The user_id is the Auth::id() - $userId
- The location_id is found by taking only() part of the request and doing a check of the locations table, and if it exists I grab the location_id - $locationId
- The remaining post data is grabbed using only() again for that data - $rentalData
All this works to this point, but how do you create and update rentals using the ids and data I've extracted, this almost works:
Location::find($locationId)->rentals()->create($rentalData);
But, need to get the $locationId and $userId into the mix somehow and it doesn't seem right to make them fillable.
I've been playing with it like this so far:
// 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);
UPDATE
So I can keep going dropped using the ORM and did this, but I'd still like to understand how Eloquent works beyond the basics I learnt watching Laracast videos so any help would be appreciated, right now I just find it really confusing:
// 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);
UPDATE
What about this solutions?
RentalRequest checks the region_id exists, and the user will always be the 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')
]);
}
I don't understand why to make it so complex?
try this:
Solution 1
$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);
Solution 2
// ->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);
这篇关于Laravel 5创建属于3个其他表的新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!