我想根据哪个用户是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吧.
谢谢你提出这个问题:model – Update the table name at runtime not working – laravel Eloquent ORM