Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Laravel 5 Erstellen eines neuen Datensatzes, der zu 3 anderen Tabellen gehört

Ich verstehe nicht, warum ich es so komplex machen soll?

versuchen Sie Folgendes:

Lösung 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);

Lösung 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);