Laravel Eloquent Relationship 2 diffrent columns - laravel

I'm trying to make a relationship between 2 models.
I have 2 models: User & Synergy
The table users has a column named employee_id, employee_id has to match to the table Synergy on the column res_id
In the model user I added:
public function Synergy(){
return $this->hasOne('App\Synergy');
}
The model synergy:
class Synergy extends Model
{
protected $connection = 'sqlsrv1';
protected $table = 'humres';
protected $primaryKey = 'employee_id';
public function user(){
return $this->belongsTo('App\User');
}
}
With this model the query is:
select top 1 * from [humres] where [humres].[user_id] = 1 and [humres].[user_id] is not null
but I want:
select top 1 * from [humres] where [humres].[res_id] = <COLUMN EMPLOYEE_ID> and [humres].[res_id] is not null

In this case, you need to explicitly state the column name for the relationships. Try this:
class Synergy extends Model
{
protected $connection = 'sqlsrv1';
protected $table = 'humres';
protected $primaryKey = 'employee_id';
public function user(){
return $this->belongsTo('App\User', 'res_id');
}
}
And in the User model;
public function synergy(){
return $this->hasOne('App\Synergy', 'employee_id');
}
Use lowercase s for the synergy relationship.
Refer to the documentation for further details.

Related

One to Many Relationship with Pivot Table and fetch related data using the with method

In Laravel 5.5 application, I have a model called Meeting and a model called Room.
Both models have a many-to-many relationship through a pivot table called MeetingSchedule.
The MeetingSchedule table has a column called schedule_by which is a foreign key to the user_id column in the User table.
I want to get the email address of the user who scheduled the meeting, when I fetch the meeting details with schedules() function of Meeting model.
I have tried the following code but it does not work:
class Meeting extends Model {
protected $table = 'Meetings';
protected $primaryKey = 'meeting_id';
protected $fillable = ['topic', 'description', 'participants_count'];
public function schedules() {
return $this->belongsToMany('App\Room', 'MeetingSchedule', 'meeting_id', 'room_id')
->using('App\MeetingSchedule')
->withPivot('schedule_id', 'start_time', 'end_time', 'scheduled_by')
->whereNull('MeetingSchedule.deleted_at')
->withTimestamps();
}
}
class Room extends Model {
protected $table = 'Rooms';
protected $primaryKey = 'room_id';
protected $fillable = ['name', 'location', 'capacity'];
public function schedules() {
return $this->belongsToMany('App\Meeting', 'MeetingSchedule', 'room_id', 'meeting_id')
->using('App\MeetingSchedule')
->withPivot('schedule_id', 'start_time', 'end_time', 'scheduled_by')
->whereNull('MeetingSchedule.deleted_at')
->withTimestamps();
}
}
class MeetingSchedule extends Pivot {
protected $table = 'MeetingSchedule';
protected $primaryKey = 'schedule_id';
public function scheduledBy() {
return $this->belongsTo('App\User', 'scheduled_by', 'user_id');
}
}
class User extends Authenticatable {
protected $table = 'User';
protected $primaryKey = 'user_id';
protected $fillable = ['username', 'email'];
public function meetingScheduledBy()
{
return $this->hasMany('App\MeetingSchedule', 'scheduled_by', 'user_id');
}
}
function getMeetingWithRelatedData($meetingId) {
return Meeting::where('meeting_id', $meetingId)
->with(['schedules'])
->first();
}

How to delete data with foreign key?

I need some help to delete a movie from my database.
I know that since I have pivot tables I will get some troubles with foreign key(my delete controller gives this error), but I don't know how to solve it.
The error i'm getting is the following:
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (sakila.film_category, CONSTRAINT fk_film_category_film FOREIGN KEY (film_id) REFERENCES film (film_id) ON UPDATE CASCADE) (SQL: delete from film where film_id = 999)
My database tables
Here are my models:
model Film:
class film extends Model{
protected $table = "film";
protected $primaryKey = 'film_id';
public $timestamps = false;
use HasFactory;
protected $sql=['film_id', 'title', 'length'];
public function category(){
return $this->belongsToMany(category::class,'film_category', 'film_id', 'category_id');
}
public function actor(){
return $this->belongsToMany(actor::class,'film_actor', 'film_id', 'actor_id');
}
}
model Category:
class category extends Model{
protected $table = "category";
protected $primaryKey = 'category_id';
public $timestamps = false;
use HasFactory;
protected $sql=['category_id','name'];
public function film(){
return $this->belongsToMany(film::class,'film_category', 'category_id', 'film_id');
}
}
model Actor:
class actor extends Model{
protected $primaryKey = 'actor_id';
public $timestamps = false;
use HasFactory;
protected $sql=['actor_id', 'first_name', 'last_name'];
public function film(){
return $this->belongsToMany(film::class,'film_actor', 'actor_id', 'film_id');
}
}
Now I need some help to make my controller function to delete records.
public function remove($film_id){
$film=film::findOrFail($film_id);
$film->delete();
return redirect('/film/view');
Thanks
To delete a movie, you must first delete the records from the Film_category and Film_actor table before you can delete your record from the Film table.
Instead do something like :
(assuming you have created your models from the Film_category and Film_actor tables)
public function remove($film_id){
$film_category = FilmCategory::where('film_id', $film_id)->delete();
$film_actor = FilmActor::where('film_id', $film_id)->delete();
$film = film::findOrFail($film_id);
$film->delete();
return redirect('/film/view');
}

Relation One to One comes Null with Laravel

I am using Eloquent to create the queries but I have a relation One to One and I am trying to get the data and it returns null.
My models are:
//Customer:
class Customer extends Model
{
protected $table = 'customers';
protected $primaryKey = 'rut';
public function user() {
return $this->hasOne(User::class, 'rut');
}
}
//User:
class User extends Authenticatable
{
use Notifiable;
protected $primaryKey = 'rut';
public function customer()
{
return $this->belongsTo(Customer::class, 'rut');
}
}
And I am doing my query like this:
$customers = Customer::with('user')->paginate(10);
It returns data but the user data is null:
activity: "Particular"
address: "AV. GRECIA 690 LOC 5"
commune_id: 12
created_at: null
email: "lavanderiaom#gmail.com"
phone: null
rut: 4180753
updated_at: null
user: null
So I wonder how can I fix it? I mean why does it come null in user? what can the problem be?
Thanks!
You Make the relation one to one in the wrong way:
Customer belongs to a User Not the opposite ..
class User extends Authenticatable
{
use Notifiable;
protected $primaryKey = 'rut';
public function customer()
{
return $this->hasOne(Customer::class, 'customers.rut','users.rut');
}
}
class Customer extends Model
{
protected $table = 'customers';
protected $primaryKey = 'rut';
public function user() {
return $this->belongsTo(User::class, 'customers.rut','users.rut');
}
}

Not able to create eloquent relationship with table which have custom primary key

When i'm trying to get user details from company Model i'm getting NULL value.
class User extends Model
{
protected $primaryKey = 'uid';
}
class Company extends Model
{
$table = 'company';
public function users(){
return $this->hasMany('App\User','user_id','uid');
}
}
class RepoController{
public function index(){
$user = Company::where('id',1)->with('user')->get();
/// Returning value but without Users
}
}`
users table should contain company_id and you should define id as company ID because company table doesn't use custom ID:
public function users()
{
return $this->hasMany('App\User', 'company_id', 'id');
}
Or just this:
public function users()
{
return $this->hasMany('App\User');
}
Also, you're trying to load user relationship, but it should be users(), so do this instead:
Company::where('id', 1)->with('users')->get();
I think your ids are in wrong position
try swapping them like
return $this->hasMany('App\User','uid','user_id');

Two foreign keys pointing to the same table / model

I have two models:
TRUCK
DRIVER
TRUCK has two fields which are FKs. Driver (FK) and Driver2 (FK).
When I try to get the truck with driver and driver2, I get two same records.
$truck = $this->instance->truck()->where('id', $id)
->with(['driver', 'driver2',])
->firstOrFail();
My Truck Model:
class Truck extends Model
{
use SoftDeletes;
protected $table = 'trucks';
protected $guarded = ['id'];
protected $dates = ['deleted_at'];
public function driver()
{
return $this->hasOne('App\Models\Driver');
}
public function driver2()
{
return $this->hasOne('App\Models\Driver');
}
My Driver Model:
class Driver extends Model
{
use SoftDeletes;
protected $table = 'drivers';
protected $guarded = ['id'];
protected $dates = ['deleted_at'];
public function truck()
{
return $this->belongsTo('App\Models\Truck');
}
I am still new to laravel and something I get stuck. Should I create another model instead maybe?
By default laravel will use default foreign key,
Eloquent assumes the foreign key of the relationship based on the
model name #Further reading
So both relation are pointing to the same FK, So you need to specify the foreign key as below
return $this->hasOne('App\Models\Driver', 'Driver');
return $this->hasOne('App\Models\Driver', 'Driver2');
Full code
class Truck extends Model
{
use SoftDeletes;
protected $table = 'trucks';
protected $guarded = ['id'];
protected $dates = ['deleted_at'];
public function driver()
{
return $this->hasOne('App\Models\Driver', 'Driver');
}
public function driver2()
{
return $this->hasOne('App\Models\Driver', 'Driver2');
}

Resources