将数据插入具有外键的表中时,完整性约束违规错误

时间:2017-06-19 11:49:17

标签: mysql laravel-5.3

我在数据库中有两个表:

公寓表

id | user_id |位置

代理商表

id |名字|电子邮件|镇

我在各自的模型中创建了两个表之间的关系,如下所示:

公寓型号:

public function agent(){
  return $this->belongsTo('App\Agent');
}

代理商型号:

 public function apartments()
 {
   return $this->hasMany('App\Apartment');
 }

当我填写表单以将数据发布到公寓表时,我收到此错误:

SQLSTATE [23000]:完整性约束违规:1048列' user_id'不能为空 (SQL:插入apartmentsuser_idPhotoLocationSizeBedroomsMasterBedrooms,  UnitdetailsHousedetailsRentupdated_atcreated_at)值(,1497870161.jpg,Nairobi,  一间卧室,1,0,单位,房子,12000,2017-06-19 11:02:42,2017-06-19 11:02:42))

这是我的控制者:

class ApartmentController extends Controller
{
    public function store(Request $request){
        //Validating the data
        $this->validate($request, array(
            'Photo'=>'required|image',
            'Location'=>'required|max:255',
            'Size'=>'required',
            'Bedrooms'=>'required',
            'MasterBedrooms'=>'required',
            'Unitdetails'=>'required',
            'Housedetails'=>'required',
            'Rent'=>'required',
        ));

        //Store data into DB
        $apartment = new Apartment;
        $apartment->user_id = Auth()->id();
        // $house->Photo = $request->Photo;
        //Saving the photo
        $image = $request->file('Photo');
        $filename = time() . '.' . $image->getClientOriginalExtension();
        $location = public_path('images/' . $filename);
        Image::make($image)->resize(735, 460)->save($location);
        $apartment->Photo = $filename;

        $apartment->Location = $request->Location;
        $apartment->Size = $request->Size;
        $apartment->Bedrooms = $request->Bedrooms;
        $apartment->MasterBedrooms = $request->MasterBedrooms;
        $apartment->Unitdetails = $request->Unitdetails;
        $apartment->Housedetails = $request->Housedetails;
        $apartment->Rent = $request->Rent;

        $apartment->save();

        Session::flash('success', 'Sent successfully!');

        return redirect::back();
    }
}

这是我将外键添加到公寓表的迁移:

public function up()
    {
        Schema::table('apartments', function (Blueprint $table) {
            $table->integer('user_id')->after('id')->unsigned();
            $table->foreign('user_id')->references('id')->on('agents');
        });
    }

apartments表中的user_id应来自代理表,或者应该是代理表中的代理ID。

我错过了什么?

0 个答案:

没有答案