[英]How to dynamically set the connection property of a model in Laravel?
I have a Laravel 5.1 App and I can dynamically set the connection property of a model doing this: 我有一个Laravel 5.1 App,我可以这样做来动态设置模型的连接属性:
class Config extends Model {
public function __construct() {
$this->connection = Session::get('conn') or abort(500, 'No conn');
}
protected $table = 'config';
}
But in Laravel 5.3+ we are not able to access the session in constructors methods without having to hack
the framework. 但在Laravel 5.3+我们不能,而无需访问构造方法会话hack
的框架。
What is the best/recommended way to do this on a model? 在模型上执行此操作的最佳/推荐方法是什么?
UPDATE: This code actually works, my problem was at the Controller level not the Model. 更新:此代码实际上有效,我的问题是在控制器级别而不是模型。
使用全局会话帮助器
$this->connection = session('conn') or abort(500, 'No conn');
It works perfectly. 它运作完美。
Using facade 使用立面
Import 进口
use Illuminate\Support\Facades\Session;
and then you can call like 然后你可以像
public function __construct() {
$this->connection = Session::get('conn') or abort(500, 'No conn');
}
Using helper function 使用辅助功能
public function __construct() {
$this->connection = session('conn') or abort(500, 'No conn');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.