Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

model - Update the table name at runtime not working - laravel Eloquent ORM

This is my model:

class Product extends GlobalModel {
    protected $table = 'product';
}

I want to update the table name oops_product instead product at runtime.

I found getTable(); to get the table name from model and its working fine:

$tableName = with(new Product)->getTable();

But when i set the table name using setTable(); as per GitHub solution, its not updating the table name.

with(new Product)->setTable("oops_produdct");

Is there anything wrong?

Help will be appreciated.

edited:

$product = new Product(); 
$product->getTable(); // output: product 
$product->setTable("oops_product"); 
$product->getTable(); // output: oops_product 

now when i run this

$product->all(); 

it executes

"select * from product" 

instead of

"select * from oops_product"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

all() is a static method that uses brand new instance and calls get() on it.

So all you need is using proper method:

$product = new Product;
$product->getTable(); // products
$product->setTable('oooops');
$product->get(); // select * from oooops
$product->first(); // select * from oooops limit 1
etc...

Just avoid using static Eloquent methods, since they obviously create new instance, that will have default table property.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...