Feb 7, 2018
12
Level 1
Dynamic Table name
Hi,
I have looked in the forum but could not apply the solutions I have found.
On a sample database like this:
categorya_products
categoryb_products
categoryc_products
.
.
.
users
Instead of creating an Eloquent model for each category, I would like to have one model and change the database table dynamically:
Product Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
// protected $table = '';
public function users()
{
return $this->belongsTo( User::class );
}
}
User Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function products()
{
return $this->hasMany( Product::class );
}
}
Controller
$categories = Category::orderBy( 'name', 'desc' )->get();
foreach ($categories as $category)
{
$products[] = \Auth::user()->products()->get();
}
How do I set the table in the product model? I have tried different ways but all failed.
Right now I am using one Model for each category table but this is kinda messy.
Cheers
Please or to participate in this conversation.