Mysql
 sql >> Base de données >  >> RDS >> Mysql

Laravel 5 Création d'un nouvel enregistrement qui appartient à 3 autres tables

Je ne comprends pas pourquoi le rendre si complexe ?

essayez ceci :

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);