Laravel模型';具有变量的s表名


Laravel Model's table name with variable

我想根据哪个用户是Auth来更改表名。

为什么?因为当我添加一个经销商时,我会为这个经销商创建一个数据库客户端,数据的名称是d.$dealer_id.clients。因此,用户需要将一个客户端添加到与自己的经销商关联的表中。

我尝试了setTable():

<?php
namespace App;
use Illuminate'Database'Eloquent'Model;
use Auth;
class Client extends Model
{
    public function setTable($table)
    {
        $this->table = 'd1clients';
        return $this;
    }
    protected $fillable = ['dealer_id', 'user_id', 'type', 'first_name', 'last_name', 'phone', 'cellphone', 'email', 'stock', 'source', 'civic', 'road', 'city', 'province', 'country', 'postal_code', 'birth_date', 'driving_liscence'];
}

但它不会将客户端保存到表中。这个:

'diclients'

应该是这样的:

'd'.Auth::user()->dealer_id.'clients'

我也试过这个东西:

$globalDealerId = Auth::user()->dealer_id;
protected $table = 'd'.$globalDealerId.'clients';
protected $fillable = ['dealer_id', 'user_id', 'type', 'first_name', 'last_name', 'phone', 'cellphone', 'email', 'stock', 'source', 'civic', 'road', 'city', 'province', 'country', 'postal_code', 'birth_date', 'driving_liscence'];

文档说setTable应该可以工作,但我不知道我做错了什么。。。

我发现了这个问题。它是如何工作的:

这个模型需要有一个功能:

<?php
namespace App;
use Illuminate'Database'Eloquent'Model;
class Client extends Model
{
    public function setTable($table)
    {
        $this->table = $table;
        return $this;
    }
    protected $fillable = ['dealer_id', 'user_id', 'type', 'first_name', 'last_name', 'phone', 'cellphone', 'email', 'stock', 'source', 'civic', 'road', 'city', 'province', 'country', 'postal_code', 'birth_date', 'driving_liscence'];
}

重要的部分是:

public function setTable($table)
{
    $this->table = $table;
    return $this;
}

然后,我转到添加客户端的位置,在这种情况下,客户端被添加到控制器内的数据库中。所以你可以这样做:

public function store(Request $request)
{
    $client =  new Client;
    $client -> setTable('d'.Auth::user()->id.'clients');
    $client -> dealer_id    = Auth::user()->dealer_id;
    $client -> user_id      = Auth::user()->id;
    $client -> type         = Request::get('type');
    $client -> first_name   = Request::get('first_name');
    $client -> last_name    = Request::get('last_name');
    $client -> phone        = Request::get('phone');
    $client -> cellphone    = Request::get('cellphone');
    $client -> email        = Request::get('email');
    $client -> city         = Request::get('city');
    $client -> stock        = Request::get('stock');
    $client -> source       = Request::get('source');
    $client -> save();

重要的一行是:

$client -> setTable('d'.Auth::user()->id.'clients');

不要忘记开头的名称空间:

use DB;

现在,属于公司A的用户A将向daclients表添加客户端。来自公司B的用户B将向dbclients表中添加客户端。

特别感谢@amir bar帮助我查询日志。感谢回答这个问题:model-在运行时更新表名不起作用-laravel Eloquent ORM