创建模型时用 laravel 返回模型

2024-03-17

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

这是我的模型

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

这是我的功能

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);
        }
    }

这是回应

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

我能怎么做?

感谢您!!


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

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

// 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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

创建模型时用 laravel 返回模型 的相关文章

随机推荐