php 从 Laravel 中的 db 模型中获取所有字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37836087/
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-08-26 01:24:44  来源:igfitidea点击:

Get all fields from db model in Laravel

phplaravellaravel-5

提问by Ivan Vulovi?

After creating model, when I try to get his attributes, i get only fields in database that are filled.

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

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

In this case I need capacity attribute too, as empty string

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

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

But for later usage (in view) I need to have all attributes, including empty ones. I know that this code works as it should, but I don't know how to change it to detect all attributes.

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

回答by patricus

You can use Schema::getColumnListing($tableName)to get an array of all the columns in the table. With that information, you can create a base array that has all the column names as keys, and nullfor all the values, and then merge in the values of your Drinkobject.

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

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')]);

        // 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])
}

回答by Rockin4Life33

What if you were to explicitly declare all the fields you want back.

如果您要显式声明想要返回的所有字段,该怎么办?

An example of something I do that is a bit more basic as I'm not using where clauses and just getting all from Request object. I still think this could be helpful to someone out there.

我做的一个例子比较基本,因为我没有使用 where 子句,只是从 Request 对象中获取所有内容。我仍然认为这可能对那里的人有所帮助。

public function getDrinkData(Request $request)
{
    // This will only give back the columns/attributes that have data.
    // NULL values will be omitted.
    //$drink = $request->all();

    // However by declaring all the attributes I want I can get back 
    // columns even if the value is null. Additional filtering can be 
    // added on if you still want/need to massage the data.
    $drink = $request->all([
        'id',
        'shopID',
        'name',
        'bottleID',
        'capacity'
    ]);

    //...

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

回答by AfikDeri

You should add a $fillable array on your eloquent model

你应该在你的 eloquent 模型上添加一个 $fillable 数组

protected $fillable = ['name', 'email', 'password'];

make sure to put the name of all the fields you need or you can use "*" to select all.

确保输入您需要的所有字段的名称,或者您可以使用“*”选择所有字段。

If you already have that, you can use the ->toArray()method that will get all attributes including the empty ones.

如果您已经拥有它,则可以使用->toArray()获取所有属性(包括空属性)的方法。

I'm using the same thing for my Postmodel and it works great with all fields including empty ones.

我对我的Post模型使用相同的东西,它适用于所有字段,包括空字段。

My model looks like this:

我的模型看起来像这样:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = ["*"];

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

}

回答by Sakil

Do you need to set the $drink variable again after checking the $drink variable?

检查完$drink 变量后是否需要再次设置$drink 变量?

you can check the following code?

您可以检查以下代码吗?

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

    if(!count($drink)>0) {
        $drink = Drink::firstOrNew(['shopId' => $request->session()->get('shopId')]);
    }
    return view('shop.drink')->(['drink' => $drink]); or
    return view('shop.drink',compact('drink'));
}

hope it will help. :) :)

希望它会有所帮助。:) :)

回答by huuuk

You can hack by overriding attributesToArraymethod

您可以通过覆盖attributesToArray方法进行破解

class Drink extends Model
{

      public function attributesToArray()
      {
          $arr = parent::attributesToArray();
          if ( !array_key_exist('capacity', $arr) ) {
              $arr['capacity'] = '';
          }

          return $arr;
      }
}

or toArraymethod

toArray方法

class Drink extends Model
{

      public function toArray()
      {
          $arr = parent::toArray();
          if ( !array_key_exist('capacity', $arr) ) {
              $arr['capacity'] = '';
          }

          return $arr;
      }
}

then

然后

$dirnk->toArray(); // here capacity will be presented even it null in db