gpt4 book ai didi

php - 带变量的 Laravel 模型表名

转载 作者:可可西里 更新时间:2023-10-31 23:29:19 25 4
gpt4 key购买 nike

我想根据授权的用户更改表名。

为什么?因为我在添加经销商的时候,为这个经销商创建了一个数据库客户端,数据的名称是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;
}

然后,我去添加客户端的地方,在这种情况下,客户端被添加到 Controller 内的数据库中。所以你去吧,你这样做:

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 - Update the table name at runtime not working - laravel Eloquent ORM

关于php - 带变量的 Laravel 模型表名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34028404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com