我是laravel的初学者.从来没有使用过框架.我创建了一个名为’tabletest’的数据库.它有两张桌子.一个是用户表,另一个是电话表.用户表有两列(id和name).电话表有3列(id phone和user_id).我正在尝试的是,我将使用表单输入并将输入发送到数据库表.尽管名称和电话已正确保存在不同的表中,但user_id(外键列)未更新.它总是0.我现在该怎么办?
迁移文件是:
用户表:
@H_404_10@public function up() { Schema::create('user',function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->timestamps(); }); }
电话表:
@H_404_10@public function up() { Schema::create('phone',function (Blueprint $table) { $table->increments('id'); $table->string('phone'); $table->unsignedInteger('user_id'); $table->timestamps(); }); }
用户模型:
@H_404_10@use App\Model\Phone; class User extends Model { protected $table = "user"; protected $fillable = ['name']; public function phone(){ return $this->hasOne(Phone::class); } }
手机型号:
@H_404_10@use App\Model\User; class Phone extends Model { protected $table = "phone"; protected $fillable = ['phone','user_id']; public function user(){ return $this->belongsTo(User::class); } }
PhoneController.PHP
@H_404_10@ PHP namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; use App\model\User; use App\model\Phone; class PhoneController extends Controller { public function store(Request $request) { User::create([ 'name' => $request->name ]); Phone::create([ 'phone' => $request->phone ]); } }
最佳答案
您永远不会指定要为其创建电话号码的用户.即使您有外键,也只能索引和约束user_id列. MysqL无法“读取”您的PHP代码并假设您正在为哪个用户创建电话号码.
有几个选择.
你可以做到这一点:
@H_404_10@$user = User::create([ 'name' => $request->input('name') ]); Phone::create([ 'phone' => $request->phone,'user_id' => $user->id ]);
或者另一种方式是:
@H_404_10@$user = User::create([ 'name' => $request->input('name') ]); $user->phone()->create([ // this uses the create method on the users phone relationship 'phone' => 999999999,]);
不确定是否也可以进行转换,但为了便于阅读,我不会推荐它(即User :: create([]) – > phone() – > create([]);)