简体   繁体   中英

Eloquent Query using Dynamic Model Laravel

I have this code which I am using to create a dynamic model in laravel

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class CRUD extends Eloquent
{   
    public $collection ;

    function __construct($attributes = [],$collection ="" )
    {  
        parent::__construct($attributes);

  $this->collection = $collection;

    }

}

and I call this class using this code

     $table='HW12345' ;
     $device_model = new CRUD([],$table);
     $device_model::limit(10)->get();

but this code return empty array . if I put this code inside the constractor

echo $collection

it print the correct value

HW12345

that mean model get the value of passed variable .

if I replaced the code

$this->collection = $collection;

to

$this->collection = 'HW12345';

it is working right without any problem and return data from collection HW12345 what is my wrong and why is that happening

$collection is a protected property.

You do not need this declaration in your model:

public $collection ;

And I would also set the collection value before calling the parent constructor.

function __construct($attributes = [], $collection = "")
    {  
        $this->collection = $collection;
        parent::__construct($attributes);
    }

Because generally, the protected properties are declared before any construct happens.

It's also very strange to use Eloquent in this manner. You remove a lot of it's static and smart features by not declaring your Models ahead of time.

Ex: You cannot do:

$results = Model::where('field', 'value')->get();

$newRecord = Model::create([values...]);

etc.

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