在运行时更新表名不起作用 - laravel Eloquent ORM [英] Update the table name at runtime not working - laravel Eloquent ORM

查看:16
本文介绍了在运行时更新表名不起作用 - 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"

解决方案

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.

这篇关于在运行时更新表名不起作用 - laravel Eloquent ORM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆