laravel / php从请求中获取对象值

时间:2018-04-08 16:01:04

标签: php laravel

我的OffersController

中有基本的商店功能
public function store(Request $request)
{     
    $offer = new Offer;
    $offer->title = $request->title;
    $offer->body = $request->body;
    $offer->region = $request->region;
    $offer->user_id = auth()->user()->id; 

    $offer->save();

    $offer->specialities()->sync($request->specialities, false); 

    return response()->json([
        'created' => true
    ], 201);
}

我的api请求正在使用如下对象调用OffersController存储函数:

{ "title": "offer title", "body": "offer body", 
"specialities": { "lang": "en", "id": "eu33", "icon": "0",
"name": "speciality name 33" }, "region": "region1" }

这给了我一个错误:Internal Server Error

"message": "SQLSTATE[HY000]: General error: 1366 Incorrect 
integer value: 'pl' for column 'speciality_id' at row 1 (SQL: 
insert into `offer_speciality` (`offer_id`, `speciality_id`) 
values (59, en))",

所以我似乎犯了明显的错误,所以我更正了我的要求:

$offer->specialities()->sync($request->specialities->id, false);

这给了我一个错误:

Internal Server Error, Trying to get property of non-object.

我在这里做错了什么?

编辑:表架构:

    Schema::create('offers', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->string('region');
        $table->mediumText('body');
        $table->integer('user_id');
        $table->timestamps();
    });

    Schema::create('specialities', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });

    Schema::create('offer_speciality', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('offer_id')->unsigned();
        $table->integer('speciality_id')->unsigned();
    });

2 个答案:

答案 0 :(得分:1)

$request->specialities是数组,因此要访问您说$request->specialities['id']

的ID

答案 1 :(得分:1)

specialities没有从数据库记录中自动保存,只有在相应地设置路径时才会发生模型绑定。

看来你没有使用specialties表主键的无符号整数,给定"id": "eu33",这是正确的吗?

首先尝试使用json_decode($request->get('specialties'));然后同步到优惠。

这里只是猜测,但也首先查询specialities记录,如:

$offer->save();

$specialties = DB::table('specialties')->where('name', $request->get('specialties')['name'])
                                       ->first();

$offer->specialities()->sync($specialities->id, false);

很难说没有看到你的架构。