I have tried to create a model in Laravel 8.x that can use different databases (Dynamically). It is currently working by setting the connection after creating an instance of the model, using Laravels build-in "setConnection" function. However, pagination on the model is not working. I get the following error:
(PDOException(code: 42S02): SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.times' doesn't exist
The problem is that the "test" database, is not the one I am currently telling the model to connect to. I am connectin to 'mysql_timer'. Is pagination reseting the DB connection to default or?
You can see my controller code here:
public function getStats(Request $request)
{
$query = new Time;
$query->setConnection('mysql_timer');
$query = $query->with(['user']);
$data = $query->paginate($length);
dd($data);
}
And my "Time" model:
class Time extends Model
{
use HasFactory;
protected $table = 'times';
public $timestamps = false;
protected $primaryKey = 'uid';
protected $fillable = [
'uid',
'mapid',
'runid',
'mode',
'style',
'rectime',
'recdate',
'strf_num',
'jump_num'
];
public function user()
{
return $this->hasOne(User::class, 'uid', 'uid');
}
}
CodePudding user response:
public function getStats(Request $request)
{
$query = DB::table("mysql_timer.times as times)
->join("users", "users.id", "=", "times.user_id")
->paginate($length);
dd($query);
}
did u try like that?
CodePudding user response:
First make model
php artisan make:time
After go model
protected $connection = "mysql_timer";
protected $table = "times";
protected $guarded = [];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
After go controller
$query = Time::query()->with("user")->paginate($length);
dd($query);