Eli*_*rin 5 php database model laravel-5.1
我想根据哪个用户是 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'];
}
Run Code Online (Sandbox Code Playgroud)
但它不会将客户端保存到表中。和这个:
'diclients'
Run Code Online (Sandbox Code Playgroud)
应该是这样的:
'd'.Auth::user()->dealer_id.'clients'
Run Code Online (Sandbox Code Playgroud)
我也试过这个东西:
$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'];
Run Code Online (Sandbox Code Playgroud)
文档说 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'];
}
Run Code Online (Sandbox Code Playgroud)
重要的部分是这个:
public function setTable($table)
{
$this->table = $table;
return $this;
}
Run Code Online (Sandbox Code Playgroud)
然后,我转到添加客户端的位置,在本例中,客户端将添加到控制器内的数据库中。所以你就这样做:
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();
Run Code Online (Sandbox Code Playgroud)
重要的一行是这一行:
$client -> setTable('d'.Auth::user()->id.'clients');
Run Code Online (Sandbox Code Playgroud)
不要忘记开头的名称空间:
use DB;
Run Code Online (Sandbox Code Playgroud)
现在,属于A公司的用户A将向daclients表添加客户。公司 B 的用户 B 将向 dbclients 表添加客户端。
特别感谢@amir bar 帮助我处理查询日志。感谢您提出这个问题:model - Update the table name at run time not work - laravel Eloquent ORM