Laravel在Form Request方法中插入FOREIGN KEY

时间:2015-11-30 06:02:16

标签: laravel-5 laravel-5.1

在我的应用程序中,一些表是关系型的,我需要将FOREIGN KEY作为User id插入到表中。从模型创建新实例然后使用save()方法我没有任何问题。但是,我想使用Form Request方法来创建和更新记录。

我收到此错误,但我不知道如何解决;

  

SQLSTATE [23000]:完整性约束违规:1452无法添加或更新>子行:外键约束失败(epaypromerchand_web_service,> CONSTRAINT merchand_web_service_user_id_foreign FOREIGN KEY(user_id)> REFERENCES usersid))(SQL:插入merchand_web_service>(updated_atcreated_at)值(2015-11-29 11:31:54,2015-11-29 11:31:54))

这是我的模特:

namespace app;
use Illuminate\Database\Eloquent\Model;
use Morilog\Jalali\jDate;

class Merchant extends Model
{
    protected $table = 'merchand_web_service';
    protected $fillable = ['customer_key', 'company_name', 'company_logo'];

    /**
     * @return mixed
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}
控制器上的

store方法:

public function store(StoreMerchantWebServiceRequest $request)
{
    Merchant::create($request->all());
    return redirect()->route('post.index');
}

StoreMerchantWebServiceRequest上课:

class StoreMerchantWebServiceRequest extends Request
{
    public function authorize()
    {
        if (Auth::check()) {
            return true;
        } else
            return false;
    }

    public function forbiddenResponse()
    {
        return Response::make(trans('message.permission_denied'), 403);
    }

    public function rules()
    {
        return [
            'agent_company_name' => 'required',
            'agent_company_logo' => 'mimes:jpg,jpeg,bmp,png|max:300',
        ];
    }
}

我的测试(在控制器中):

public function store(StoreMerchantWebServiceRequest $request)
{
    $order = Merchant::create($request->all());
    $this->user_id = Auth::user()->id;
    $order->save();
    return redirect()->route('post.index');
}

1 个答案:

答案 0 :(得分:1)

处理这种情况的一种非常简单的方法是在控制器的store方法中:

public function store(StoreMerchantWebServiceRequest $request)
{
    $merchantData = $request->all();
    $merchantData['user_id'] = Auth::user()->id;
    Merchant::create($merchantData);
    return redirect()->route('post.index');
}