associate() 和 1tomany 奇怪的行为

associate() and 1tomany strange behavior

我使用 Laravel 5.3 并使用 "store" 方法创建了一个简单的控制器,这是关系的 "belongTo" 方面。 其他 2 个模型正确包含 "hasMany" 函数。

public function store(Request $request)
{

    $user_id = JWTAuth::parseToken()->authenticate()->id;
    if(!Vehicle::where('id', '=', $request->vehicle_id)->exists()){
        return $this->response->error('could_not_create_trip_errore_veicolo', 500);
    }
    if(!Ztl::where('id', '=', $request->ztl_id)->exists()){
        return $this->response->error('could_not_create_trip_errore_ztl', 500);
    }
    $request->request->add(['user_id' => $user_id]);

    $trip = new Trip($request->all());

    //$trip->user()->associate($request->user_id);
    //$trip->vehicle()->associate($request->vehicle_id);
    //$trip->ztl()->associate($request->ztl_id);

    if(true)
    {
        if($trip->save()){

            return $this->response->created();
        }else return $this->response->error('could_not_create_trip', 500);
    }else return $this->response->error('could_not_create_trip_current_user_Error', 500);

}

第一个问题是: 为什么如果注释或取消注释 "associate" 方法,什么都没有改变。 我是否需要将这些放在控制器上,或者我还不太了解此方法的含义。

第二个:

如果我向我的控制器发送一些数据,使用表格进行测试,"required" 是 3 个外键。 如果我发送的号码不在我的另一个 "hasmany" table 上,则会出现错误,但如果尝试插入类似 "2dsksk" 的内容,其中 2 是 [=26= 的正确 ID ] table然后是一个随机字符串,id被insert取为2,这样对吗? 验证只取数据的 "correct" 数字部分……问题是,为什么?这是安全的吗?

associate 只是设置 child 的外键。这意味着您之后需要保存您的模型。

 $trip->user()->associate($request->user_id);
 $trip->save();

对于第二个问题,可能MySQL 根据列的数据类型截断数据。如果您不希望这种情况发生,您可能需要将 MySQL 设置为严格模式。

http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sql-mode-strict