问题
This is my restaurant table:

the restaurant table has a adminID
field . and this is the admin table:

I have a form that has the values of both the restaurant and the admin,
This is Admin model:
class Admin extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
public function restaurant(){
return $this->belongsTo('Restaurant', 'ID');
}
This is Restaurant model:
class Restaurant extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
public function admin(){
return $this->hasOne('Admin', 'adminID');
}
This is the RestaurantsController for storing a new restaurant
$input = Input::all();
$validation = Validator::make($input, Admin::$rules);
if($validation->passes()){
$validation = Validator::make($input, Restaurant::$rules);
if ($validation->passes())
{
$admin = Admin::create(Input::only('username', 'password', 'mobileNumber', 'firstName', 'lastName'));
as you see now I have the $admin
variable,
My Question
what is the statmnet that I need to insert a new restaurant
- please note that I can take the adminID from $admin->id
- please note that the restaurant has a null columns like logo and addressManualID
回答1:
At first, you don't need to implement UserInterface
and RemindableInterface
and and also don't use use UserTrait, RemindableTrait
to create all of your models but only the User
model if you have a User
model for user authentication (log in/out). If the Admin
model is being used as a replacement of the User
model then you need to implement those interfaces and also need to use those traits as well. Also you need to explicitly declare the protected $table
property to assign the table name which is being used for Admin
model (If you are not using User
model) and also you need to change some settings in app/config/auth.php
file as given below:
'model' => 'Admin',
'table' => 'admins', // Could be anything else, same as protected $table property
Then try following to save the the related model when creating Admin
:
//...
if ($validation->passes()) {
$admin = Admin::create( Input::only('username', ...) );
$restaurent = new Restaurant(Input::only(...));
$admin->restaurant()->save($restaurent);
}
回答2:
You will want to use associate()
method.
$restaurant = Restaurant::find(10);
$restaurant->admin()->associate($admin);
$restaurant->save();
Reference: http://laravel.com/docs/eloquent#inserting-related-models
来源:https://stackoverflow.com/questions/24274903/laravel-insert-a-new-row-that-has-a-key-from-another-table-and-a-null-columns