sql >> Base de Datos >  >> RDS >> Mysql

Laravel 5 Crear un nuevo registro que pertenece a otras 3 tablas

No entiendo por qué hacerlo tan complejo?

prueba esto:

Solución 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);

Solución 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);