gpt4 book ai didi

php - 从 Laravel 中的数据库模型中获取所有字段

转载 作者:可可西里 更新时间:2023-11-01 00:00:03 27 4
gpt4 key购买 nike

创建模型后,当我尝试获取他的属性时,我只得到数据库中已填充的字段。

    ----------------------------------------------
DB: | id | shopID | name | bottleID | capacity |
----------------------------------------------
| 1 | 8 | Cola | 3 | |
----------------------------------------------

在这种情况下,我也需要 capacity 属性,作为空字符串

public function getDrinkData(Request $request)
{
$drink = Drink::where('shopId', $request->session()->get('shopId'))->first();

if($drink) {
$drink = $drink->attributesToArray();
}
else {
$drink = Drink::firstOrNew(['shopId' => $request->session()->get('shopId')]);
$drink = $drink->attributesToArray(); // i want to get even empty fields
}
return view('shop.drink')->(['drink' => $drink])
}

但为了以后使用(在 View 中),我需要拥有所有属性,包括空属性。我知道这段代码可以正常工作,但我不知道如何更改它以检测所有属性。

最佳答案

模型属性是通过从数据库中读取数据来填充的。当使用 firstOrNew() 并且记录不存在时,它会生成模型对象的 new 实例而不从数据库中读取,因此它具有的唯一属性是那些手动分配的。此外,由于数据库中还没有记录,您不能只是重新读取数据库来获取丢失的数据。

在这种情况下,您可以使用 Schema::getColumnListing($tableName) 获取表中所有列的数组。有了这些信息,您可以创建一个基本数组,将所有列名称作为键,所有值都为 null,然后合并到 Drink 对象的值中.

public function getDrinkData(Request $request)
{
// firstOrNew will query using attributes, so no need for two queries
$drink = Drink::firstOrNew(['shopId' => $request->session()->get('shopId')]);

// if an existing record was found
if($drink->exists) {
$drink = $drink->attributesToArray();
}
// otherwise a new model instance was instantiated
else {
// get the column names for the table
$columns = Schema::getColumnListing($drink->getTable());
// create array where column names are keys, and values are null
$columns = array_fill_keys($columns, null);

// merge the populated values into the base array
$drink = array_merge($columns, $drink->attributesToArray());
}

return view('shop.drink')->(['drink' => $drink])
}

如果您使用的是 firstOrCreate(),则在记录不存在时会创建一条新记录。由于现在数据库中有记录,您可以简单地从数据库中重新读取记录以填充所有模型属性。例如:

public function getDrinkData(Request $request)
{
$drink = Drink::firstOrCreate(['shopId' => $request->session()->get('shopId')]);

// If it was just created, refresh the model to get all the attributes.
if ($drink->wasRecentlyCreated) {
$drink = $drink->fresh();
}

return view('shop.drink')->(['drink' => $drink->attributesToArray()])
}

关于php - 从 Laravel 中的数据库模型中获取所有字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37836087/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com