Laravel whereRelation with another database connection - php

I am just using Laravel whereRelation. It runs smooth and as expected if the relations between 2 tables is in the same database (DB_A). The problem is when I have to use 2 databases (DB_A and DB_B). In the model relationship I put the connections and there is no problem
// Model user DB_A
protected $connection = 'mysql';
public function address()
{
return $this->hasOne(Address::class, 'id_user');
}
// Model address DB_B
protected $connection = 'mysql2';
protected $table = 'address';
public function user()
{
return $this->belongsTo(User::class, 'id_user');
}
In the query I want to get all the relationship between those 2 tables. The query like:
$data = User::with('address')->reorder('id', 'desc');
$data = $data->whereRelation('address', 'status', '=', 'verified');
I got the error say that table address doesn't exist in DB_A which is belong to DB_B. If i remove the line whereRelation takeplace it doesn't give any errors. How to handle or specify the database name and table name in whereRelation?
EDIT: Both DB_A and DB_B is in different Host.

Try it will hopefully work
Model address DB_B
class User extends Eloquent {
// *******default connection************
public function address() {
return $this->setConnection('mysql')->belongsTo(Address::class, 'id_user');
}
}
Model address DB_B
class Address extends Eloquent {
// *******default connection************
public function user() {
return $this->setConnection('mysql2')->belongsTo(User::class, 'id_user');
}
}

Related

Laravel Pagination not working after setConnection() on eloquent model

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);

why laravel 6 many-to-many relationship does not working?

Hi I simply want to get permissions of the role, I am trying following
$r = Role::find(1);
dd($r->permissions);
The above script does not return any permission however you can see there is data in the below tables. I also tried following but no luck
$role = Role::with('permissions')->where('id', 1)->first();
I have data in the table as you can see
Table:tes_permissions
Table: tes_roles
Table: tes_permission_role
And following are Models
class Permission extends Model
{
protected $table = 'tes_permissions'
public function roles()
{
return $this->belongsToMany('App\Role');
}
}
And
class Role extends Model
{
protected $table = 'tes_roles';
public function permissions() {
return $this->belongsToMany('App\Permission', 'tes_permission_role', 'permission_id', 'role_id');
}
}
Can someone kindly guide me what can be the issue, I would appreciate.
You mixed the order of properties in the belongsToMany(). The third argument is specifying the ID for the model defining the relationship. So change to the following:
public function permissions() {
return $this->belongsToMany('App\Permission', 'tes_permission_role', 'role_id', 'permission_id');
}
And on the Permission model, also define it to be sure.
public function roles()
{
return $this->belongsToMany('App\Role', 'tes_permission_role', 'permission_id', 'role_id');
}

Laravel 5.4 Auth::User() with relationship not working

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);

Eloquent model relationship for intermediate table

Consider the following table structure:
user table
id
name
lang_region_id
lang_region table
id
lang_id
region_id
lang table
id
name
region table
id
name
Fairly new to the Laravel framework, but trying to setup Eloquent models and relationships to an existing database. I want to establish the relationship between my user model and the lang and region models. The lang_region table defines what language and region combinations are available and then we can link each user to a valid combination.
I have read through the Laravel documentation several times looking for the proper relationship type, but is seems that the Many to Many and Has Many Through relationships are close, but since our user.id isn't used in the intermediate table I may be out of luck.
Sorry for the amateur question, but just getting used to Laravel and ORMs in general.
I would use the lang_region table as both a pivot table and a regular table with its own model.
class LangRegion extends model
{
protected $table = 'lang_region';
public function language()
{
return $this->belongsTo(Language::class, 'lang_id');
}
public function region()
{
return $this->belongsTo(Region::class);
}
public function users()
{
return $this->hasMany(User::class);
}
}
class User extends model
{
protected $table = 'user';
public function langRegion()
{
return $this->belongsTo(LangRegion::class);
}
}
class Language extends model
{
protected $table = 'lang';
public function regions()
{
$this->belongsToMany(Region::class, 'lang_region', 'lang_id', 'region_id');
}
public function users()
{
$this->hasManyThrough(User::class, LangRegion::class, 'lang_id', 'lang_region_id');
}
}
class Region extends model
{
protected $table = 'region';
public function languages()
{
$this->belongsToMany(Language::class, 'lang_region', 'region_id', 'lang_id');
}
public function users()
{
$this->hasManyThrough(User::class, LangRegion::class, 'region_id', 'lang_region_id');
}
}
If I understand what you want correctly:
class User extends Model {
private function lang_region() {
return $this->hasOne(LangRegion::class)
}
public function lang() {
return $this->lang_region()->lang();
}
public function region() {
return $this->lang_region()->region();
}
}
class LangRegion extends Model {
public function lang() {
return $this->belongsTo(Lang::class);
}
public function region() {
return $this->belongsTo(Region::class);
}
}

Eloquent model relationship returning as null

I have a laravel model
class Project extends Eloquent {
public static $timestamps = true;
public $includes = array('members','members.memberdata');
public function tasks() {
return $this->has_many('Usertask','project_id');
}
public function members() {
return $this->has_many('Projectmember','project_id');
}
}
and a related models
class Projectmember extends Eloquent {
public static $table = "project_members";
public static $timestamps = true;
public function project() {
return $this->belongs_to('Project');
}
public function memberdata() {
return $this->has_one('Usermetadata','user_id');
}
}
class Usermetadata extends Eloquent {
public static $table = "users_metadata";
public function user() {
return $this->belongs_to('User');
}
public function member() {
return $this->belongs_to('Projectmember','user_id');
}
}
When i attempt to retrieve a single project model like so
$project = Project::find($id);
return Response::eloquent($project);
my json output looks like this
{"id":1,"user_id":1,"name":"UberWork","description":"Web based project management \/ task management app","target_date":"2013-11-15 00:00:00","budget":null,"status":0,"created_at":"2013-04-16 20:13:59","updated_at":"2013-04-16 20:13:59","members":[{"id":1,"project_id":1,"user_id":1,"created_at":"2013-04-16 20:13:59","updated_at":"2013-04-16 20:13:59","memberdata":{"user_id":1,"first_name":"Tamarakuro","last_name":"Foh","photo":"","company_name":null,"phone":null,"package":"free","subscription_start":"0000-00-00 00:00:00","subscription_end":"0000-00-00 00:00:00","api_key":"12b14a7d3ca48c53bb5b1a88fa3eca3b"}},{"id":3,"project_id":1,"user_id":3,"created_at":"2013-04-16 20:13:59","updated_at":"2013-04-16 20:13:59","memberdata":{"user_id":3,"first_name":"Ebere","last_name":"Uche","photo":"","company_name":"Chronotech Labs","phone":null,"package":"free","subscription_start":"0000-00-00 00:00:00","subscription_end":"0000-00-00 00:00:00","api_key":"ab446bd9ffbb898e818a892c7401e0f6"}},{"id":4,"project_id":1,"user_id":2,"created_at":"2013-04-17 08:13:00","updated_at":"2013-04-17 08:13:00","memberdata":null}]}
My database look like this;
Users
id
email
password
ip_address
active
...
users_metadata
id
user_id
first_name
last_name
profile_photo
...
Projects
id
user_id
name
description
status
...
project_members
id
project_id
user_id
My question is why is the last member of the project having its memberdata as "null", while the others are not null. Am i doing something wrong?
Relationships in Eloquent always link a primary key (pk) with a foreign key (fk). However, you're trying to base a relationship on two foreign keys, skipping out a relationship. The only Eloquent solution is to include the extra relationship step. Here are some models (I've ommited the relationships we don't need for this example)...
class Project extends Eloquent {
public static $timestamps = true;
public $includes = array('members','members.user', 'members.user.metadata');
public function members()
{
return $this->has_many('Projectmember','project_id');
}
}
class Projectmember extends Eloquent {
public static $table = "project_members";
public static $timestamps = true;
public function user()
{
return $this->belongs_to('User');
}
}
class User extends Eloquent {
public static $timestamps = true;
public $hidden = array('password', 'ip_address');
public function metadata()
{
return $this->has_one('Usermetadata');
}
}
class Usermetadata extends Eloquent {
public static $table = "users_metadata";
public function user() {
return $this->belongs_to('User');
}
}
I can see why you'd want to skip the relationship, but sadly it's not possible with relationships.

Categories