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');
}
}
You can use on($connection) to begin querying the model on a given connection:
$data = Time::on('mysql_timer')->with(['user'])->paginate($length);
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?
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);
Related
I have Table Vendors (for test Auth relationship) and Table Vendor_users,
But i use Auth::user() it not relationship
And This Database
In Vendor model
protected $table = 'vendor_users';
public function Vendor_test(){
return $this->belongsTo(Vendor_test::class);
}
And Vendor_test model
protected $table = 'vendors';
public function Vendor(){
return $this->hasMany(Vendor::class);
}
from chat and your current table structure, you should have relation like this
in Vendor Model
public function vendor_contact()
{
return $this->belongsTo(Vendor_contact::class, 'vendor_contact_id');
}
in Vendor_contact Model
protected $primaryKey = 'vendContactId'; //check this
public function vendor()
{
return $this->hasOne(Vendor::class, 'vendor_contact_id');
}
Now use lazy eager loading for loading vendor_contact relationship
Auth::user()->load('vendor_contact');
dd(Auth::user());
As per the discussion and the table structure you have,
Add the relation function in your model vendor_users.
protected $table = 'vendor_users';
public function vendor_contact()
{
return $this->belongsTo(Vendor_contact::class, 'vendor_contact_id');
}
get the user with the vendor_contact and check
$user = Auth::user()->with('vendor_contact')->first(); // As you asked with for auth
//OR
$user = Auth::user()->load('vendor_contact'); // From the rkj answer as I found this good.
// OR
$user = Vendor::find(1)->with('vendor_contact')->first();
dd($user);
in this code as:
$latestHerbsInformation = \App\ContentCategories::find('14')->contents->take(5);
which that work fine i want to use inRandomOrder() to get random rows from contents, Contents and ContentCategories are belongsToMany RelationShips and this code:
$latestHerbsInformation = \App\ContentCategories::find('14')->contents->inRandomOrder()->take(5);
don't work for me.
Contents model:
class Contents extends Model
{
use Sluggable;
protected $table = 'contents';
protected $guarded = ['id'];
public function categories()
{
return $this->belongsToMany(ContentCategories::class);
}
}
ContentCategories model:
class ContentCategories extends Model
{
protected $table = 'contents_categories';
protected $guarded = ['id'];
public function contents()
{
return $this->belongsToMany(Contents::class);
}
}
i get this error:
Method inRandomOrder does not exist.
how can i solve this problem? Thanks in advance
The correct query is:
\App\ContentCategories::find('14')->contents()->inRandomOrder()->take(5)->get();
Because this will execute the query and will return a collection:
\App\ContentCategories::find('14')->contents
I have a User-Roles model, using Laravel 4 where a user can have many roles, using Eloquent. I can access all roles linked to a user easily using this code :
class User extends Model {
protected $table = 'user';
protected $fillable = array('name');
public function rolesLinked() {
return $this->hasMany('App\UserRoleLink', 'user_id');
}
}
I've been trying to obtain the roles that are not linked to a user, to display on the specific user's page in a select box. Using this function, included in the User class.
public function rolesNotLinked() {
$user = this
$roles = Roles::whereDoesntHave('App\UserRoleLink',function($query) use ($user){
$query->where('user_id',$user->id);
});
}
The problem is, calling this function gives me the following error.
Call to undefined method Illuminate\Database\Query\Builder::App\UserRoleLink()
I've tried using has with < 1 to see if the function was problematic, but after reading this and the online source code, the function call pretty much does what I've tried.
Is something wrong in my function call, or have I messed up configurations somewhere?
For reference, here are my other Model classes:
class UserRoleLink extends Model{
protected $table = 'user_role_link';
protected $fillable = array('role_id','user_id);
public function role() {
return $this->hasOne('App\Role', 'role_id');
}
}
class Role extends Model{
protected $table = 'role';
protected $fillable = array('name');
}
EDIT: I've found out that I messed up by fillables when I copy-pasted. It didn't fix the issue, but I guess that's one step closer.
To use whereDoesntHave method, you must add the relation in your Role Model.
class Role extends Model{
protected $table = 'role';
protected $fillable = array('name');
public function UserRoles() {
return $this->hasMany('App\UserRoleLink', 'id');
}
}
Also, the whereDoesntHave method first parameter is not thte model but the function of the relation:
public function rolesNotLinked() {
$user = this
$roles = Roles::whereDoesntHave('UserRoles',function($query) use ($user){
$query->where('user_id',$user->id);
});
}
I have this annoying problem when trying to execute a hasMany method:
I have a Task model, of which I want to retrieve all the states
class Task extends Eloquent {
protected $guarded = array();
public static $rules = array();
public function states(){
return $this->hasMany('TaskState','task_id');
}
...from this TaskState model (db has columns: task_id, user_id, status)
class TaskState extends Eloquent {
public $table= "taskstates";
protected $guarded = array();
public static $rules = array();
public function task(){
return $this->belongsToMany('Task','task_id');
}
However when I try to execute this,
$task = Task::find($id);
return $task->states;
it keeps giving this error:
Call to undefined method TaskState::newQuery()
I'm stuck on this for like two days. Would anyone know what the problem might be here?
Thanks in advance!
If there is one-to-many relationship between models, then you should use 'belongsTo' in TaskState instead of 'belongsToMany;
I am having issues getting the relationship array back when eager loading in laravel 4. for example:
controller:
foreach (Apps::with('extra')->get() as $app)
{
print_r($app->toArray());//returns array but my relationship array at the bottom says null
echo $app->extra; //this will show my relationship details
}
model:
class Apps extends Eloquent
{
protected $connection = 'mysql_2';
protected $table = 'apps';
public $timestamps = false;
protected $primaryKey = 'name';
public function host()
{
return $this->belongsTo('Hosts','name');
}
public function extra()
{
$this->primaryKey='app_ip';
return $this->hasone('Extra','ip');
}
//other functions below.......
}
class Extra extends Eloquent
{
protected $connection = 'mysql_3';
protected $table = 'extra';
public $timestamps = false;
protected $primaryKey = 'ip';
public function app(){
return $this->belongsTo('Apps', 'app_ip');
}
mysql:
My mysql tables were not created through laravel they were previously existent. the app_ip column in the Apps table relates to the ip column in the extra table. it is a 1 to 1 relationship and I have specified the primary key in the relationship function. I am getting relationships back so I know that it is working.
I am able to get relationship data back when I call the function directly, but it does not show the relationship data when I try and print the full array. The main goal is to be able to return both the relationship columns and the app columns in one response.
You need to do this:
$apps = Apps::all();
$apps->load('extra');
foreach ($apps as $app)
{
print_r($app->toArray()); // prints your relationship data as well
}
What you have should work and iterating through the collection or using ->load() to eager load shouldn't make a difference. Are you using the visible restriction on your models? If so you will need to include the relationships.
class Apps extends Eloquent {
protected $visible = array(
'id',
'name',
'created_at',
'extra', // Make the relationship 'visible'
);
public function extra()
{
return $this->hasMany('Extra');
}
}