如何更新拉拉维尔雄辩中的外键ide值?

我对拉拉维尔很陌生,我无法在拉拉维尔文档和这里找到这个问题的答案。我想这只是一个如何搜索它的问题,因为我非常确定这是一个常见的情况。


我有两个模型处于关系中(这是一个简化的情况),我通过资源文件检索我需要的信息,但我无法了解如何正确存储或更新信息。下面是一个代码示例:


Models\Company.php


class Company extends Model

{

    protected $fillable = [

        'name', 'blablabla', 'country_id', 'blablabla2',

    ];


    public function country() {

        return $this->belongsTo(Country::class);

    }

}

Models\Country.php


class Country extends Model

{

    protected $fillable = [

        'code', 'name', 'prefix', 'tax_code_id',

    ];


    public function companies() {

        return $this->hasMany(Company::class);

    }

}

然后我有一个公司控制器文件来管理API请求:


Controllers\CompanyController.php


class CompanyController extends BaseController

{

    public function index()

    {

        $companies = Company::paginate();

        $response = CompanyResource::collection($companies)->response()->getData(true);


        return $this->sendResponse($response, 'Companies retrieved successfully');

    }


    public function store(Request $request)

    {

        $input = $request->all();


        $validator = Validator::make($input, $this->validation_rules);


        if($validator->fails()){

            return $this->sendError('Validation error.', $validator->errors());

        }


        $company = Company::create($input);


        return $this->sendResponse($company->toArray(), 'Company added successfully.');

    }

}


...


    public function update(Request $request, Company $company)

    {

        $input = $request->all();


        $validator = Validator::make($input, $this->validation_rules);


        if($validator->fails()){

            return $this->sendError('Validation error.', $validator->errors());

        }


        $company->update($input);


        return $this->sendResponse($company->toArray(), 'Company updated successfully.');

    }


我希望更新公司表中记录1 country_id字段,以便它与有效载荷匹配(因此从100到200),但这并没有发生。


我可以编辑前端逻辑,以便仅发送有效负载中的country_id,因为我不打算更新国家/地区表,并且所有这些附加信息都是多余的,但我想知道如何使用Laravel在控制器中管理它。


你介意帮我吗?提前致谢。


牧羊人nacy
浏览 141回答 1
1回答

弑天下

如果您希望它现在与代码一起使用,则需要在要发送的根 JSON 对象中具有该对象。因为这是您填写id的方式。在我看来,这不是最好的方法,但这就是为什么您的更新目前不起作用的原因。country_id{    "name": "something",    "blablabla": "blablabla3",    "country_id": 200,    ...我真的很喜欢发送完整对象的方法。通常填写id是不好的,因为它会干扰关系的工作方式。Laravel会在你交往时设置你的关系,如果没有,你不能保证在填完后有正确的关系。因此,我将获取ID并将国家对象与公司相关联。在与此类似的逻辑中。// only fill non relation fields, fill used as save is needed after associate()$company->fill($request->only(['name', 'blabla']));$company->country()->associate(Country::find($request->get('country')['id']));//associate does not save$company->save();
打开App,查看更多内容
随时随地看视频慕课网APP