user7432810
user7432810

Reputation: 695

Laravel settable doesn't work as expected

EDIT: Just to save time as some people kindly add response but don't read comments. It appears that although we can set the table on the fly and it works for get and take and all BUT it doesn't work for update.

Now the original question:

I have a problem with dynamic table name that I can best explain by the code I tried: This is what I do and works:

$ymodel = new \App\YCenter;
$ymodel->setTable('tableNo1');
$tops = $ymodel->take(10)->get();
var_dump($tops);

But this is what I tried:

$ymodel = new \App\YCenter;
$ymodel->setTable('tableNo1');

$ymodel->updateOrCreate(
    ['url' => 'heyhey','article_id' => 1],
        ['text'=>'texttext']
); 

And got this error:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 
'mydatabase.y_centers' doesn't exist (SQL: insert into `y_centers`...

Any idea? Thanks in advance.

Edit: The ideas is to set the table on the fly and that's why Im doing it this way. I don't want to set the table on the model itself.

Upvotes: 3

Views: 1272

Answers (1)

Mister Verleg
Mister Verleg

Reputation: 4303

Some laravel methods make a new instance of an object

This will not work:

 $someModel = new RunTimeObject();
 $someModel->setTable('newTable');
 return $someModel->all();

This is due to that all() creates a new someModel in the background. If you use a non-static method: ( for example ->get() )

    $runtime = new RunTimeObject();
    $runtime->setTable('newTable');
    return $runtime->get();

It will work, so you can only use non static methods

Upvotes: 3

Related Questions