Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
613 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...