简体   繁体   中英

Why query statement results on eloquent orm is returning null values

I'm new to this questions thing so please bear with me.

I'm using Eloquent as my PHP database library. So I created a class that extends from Illuminate\\Database\\Eloquent\\Model and tried to query one single record. When I print the results I know it is fetching the information, as you can see by the protected attributes , but somehow the public attributes of the record are NULL.

Am I missing some previous configuration, or is there another reason for that?

Here's my structure:

The Model, Plantilla.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Plantilla extends Model
{
    /**
     * @var string
     */
    protected $primaryKey = 'cod_plantilla';
    /**
     * @var string
     */
    protected $table = 'plantilla';
    protected $connection = 'mysql';

    public function __construct()
    {
        #attributes
        parent::__construct();
        Database2::init();
    }
}

Database.php

<?php

namespace App\Models;

use Illuminate\Database\Capsule\Manager as Capsule;

class Database2
{
    private static $db;

    static public function init()
    {
        if (is_null(self::$db)) {
            $capsule = new Capsule;

            $capsule->addConnection([
                'driver' => 'mysql',
                'host' => getenv('DB_HOST'),
                'database' => getenv('DB_NAME'),
                'username' => getenv('DB_USER'),
                'password' => getenv('DB_PASS'),
                'charset' => 'utf8',
                'collation' => 'utf8_unicode_ci',
                'prefix' => '',
            ], 'mysql');

            // Make this Capsule instance available globally via static methods... (optional)
            $capsule->setAsGlobal();

            // Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
            $capsule->bootEloquent();
        }
    }
}

index.php

$p = Plantilla::where('cod_plantilla', 35)->first();
var_dump($p);

Result

object(App\Models\Plantilla)[251]
  protected 'primaryKey' => string 'cod_plantilla' (length=13)
  protected 'table' => string 'plantilla' (length=9)
  protected 'connection' => string 'mysql' (length=5)

  # Values I need
  public 'cod_area_interna' => null
  public 'cod_tipo_plantilla' => null
  public 'nombre' => null
  public 'detalle' => null
  public 'personalizada' => null
  public 'fecha' => null
  # Values I need

  protected 'keyType' => string 'int' (length=3)
  public 'incrementing' => boolean true
  protected 'with' => 
    array (size=0)
      empty
  protected 'withCount' => 
    array (size=0)
      empty
  protected 'perPage' => int 15
  public 'exists' => boolean true
  public 'wasRecentlyCreated' => boolean false

  # Same values I need but they're protected
  protected 'attributes' => 
    array (size=7)
      'cod_plantilla' => int 35
      'cod_area_interna' => int 2
      'cod_tipo_plantilla' => int 1
      'nombre' => string 'Some' (length=32)
      'detalle' => string 'Some' (length=142)
      'personalizada' => null
      'fecha' => string '2020-06-25 12:15:13' (length=19)
  protected 'original' => 
    array (size=7)
      'cod_plantilla' => int 35
      'cod_area_interna' => int 2
      'cod_tipo_plantilla' => int 1
      'nombre' => string 'Some' (length=32)
      'detalle' => string 'Some' (length=142)
      'personalizada' => null
      'fecha' => string '2020-06-25 12:15:13' (length=19)
  protected 'changes' => 
...

As the documentation states, you can do something like this

<?php

$flights = App\Models\Flight::all();

foreach ($flights as $flight) {
    echo $flight->name;
}

So you can access the attributes aka table columns values.

In my case those are:

  • cod_plantilla
  • cod_area_interna
  • cod_tipo_plantilla
  • nombre
  • detalle
  • personalizada
  • fecha

I am not sure what you are actually asking about here.

The attributes are not 'properties' of the class. They are held in a protected array named $attributes . If you want to access them you can do that in the way the documentation says you can.

You could access them via the dynamic property:

$p = Plantilla::find(35);

echo $p->nombre;

Via array access:

echo $p['nombre'];

You can get the array of attributes themselves:

dump($p->getAttributes());

Serialize the model's attributes (and loaded relationships) to an array:

dump($p->toArray());

Or even get the serialized model as JSON:

echo $p->toJson();

It looks to me like Eloquent is actually performing exactly as it should be!

Eloquent does a lot of automagic with PHP magic methods. What looks like regular PHP object properties are actually dynamically accessed via __get() and __set() from the $attribute property.

In your example you have this:

$p = Plantilla::where('cod_plantilla', 35)->first();

Using Tinker (if you're new to Laravel, it's easiest to use php artisan tinker to figure out this sort of stuff), you should be able to just try accessing your database columns like this:

> $p->cod_plantilla;
35
> $p->fecha;
'2020-06-25 12:15:13'

You should find your values are returned, even though var_dump() shows nothing!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM