php laravel如何插入外键

时间:2014-06-18 11:18:32

标签: php mysql laravel laravel-4 blade

我有两张表:

管理

ID | username | password | mobileNumber | firstName | lastName

餐厅:

website | adminID | name

我有一个包含此数据的html表单

restaurantName
website
username
password
mobileNumber
firstName
lastName

当我提交该表单时,我想将数据插入管理表,然后将带有adminID的数据插入到餐厅表中:

我试过了:

$input = Input::all();
$admin = Admin::create(Input::only('username', 'password', 'mobileNumber', 'firstName', 'lastName'));

$data = [
   'name' , 
   Input::get('restaurantName'), 
   'website' => Input::get('website')
];

$restaurant = new Restaurant($data);
$admin->restaurant()->save($restaurant);

但我得到了这个例外:

BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::save()
你可以帮忙吗?

管理模型

class Admin  extends Eloquent implements UserInterface, RemindableInterface {

use UserTrait, RemindableTrait;

public function restaurant(){
    return $this->belongsTo('Restaurant', 'ID');
}

餐厅模特

class Restaurant extends Eloquent implements UserInterface, RemindableInterface {

use UserTrait, RemindableTrait;

public function admin(){
    return $this->hasOne('Admin', 'adminID');
}

1 个答案:

答案 0 :(得分:1)

尝试:

$restaurant->admin()->associate($admin);
$restaurant->save();