使用 laravel 在创建时返回模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45404630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:24:29  来源:igfitidea点击:

Return model with laravel when it was created

phpjsonlaravelpostgresql-9.4

提问by Michael Zapata

I need to send a new model saved as json to front but I can't see column organizationid in response

我需要将保存为 json 的新模型发送到前面,但我看不到列组织 ID 作为响应

This is my model

这是我的模型

class Organization extends Model
{
    protected $table = "core.organizations";
    protected $fillable = ['description'];
    public $primaryKey = "organizationid";
    public $incrementing = false;
    public $timestamps = false;
}

and this is my function

这是我的功能

public function saveOrganization(Request $request)
    {
        try {
            $description = $request->input('description');
            $organization = new Organization();
            $organization->description = $description;
            $organization->save();
            if (!$organization) {
                throw new \Exception("No se guardo la organizacion");
            }           
            return response()->json([
            'organization' => $organization,
            ], 200);
        } catch (\Exception $ex) {
            return response()->json([
                'error' => 'Ha ocurrido un error al intentar guardar la organización',
            ], 200);
        }
    }

and this is response

这是回应

{"organization":{"description":"Restobar"}}

How can I do?

我能怎么做?

Thanks you!!

谢谢!!

回答by patricus

Since you've created a new object, and not retrieved one from the database, the only attributes it will know about are the ones that you set.

由于您创建了一个新对象,并且没有从数据库中检索到一个对象,因此它唯一知道的属性就是您设置的属性。

If you'd like to get the rest of the fields on the table, you will need to re-retrieve the object after you save it.

如果您想获取表中的其余字段,则需要在保存对象后重新检索该对象。

// create the new record.
// this instance will only know about the fields you set.
$organization = Organization::create([
    'description' => $description,
]);

// re-retrieve the instance to get all of the fields in the table.
$organization = $organization->fresh();

回答by skido

$savedOrganization = Organization::create(
    [
        'description' => $description
    ]
);

return response()->json([
        'organization' => $savedOrganization,
        ], 200)

And this code is useless

而这段代码没用

if (!$organization) {
    throw new \Exception("No se guardo la organizacion");
}