yii 1.1.x ar relation for composite forign key - for-loop

I have three tables
Boooking
id, -> primary key
name
Ticket
booking_id, (primary key)
seq , (primary key)
name
TicketAllocation
id, (primary key)
booking_id, (foreign key)
seq, (foreign key)
name,
date
Ticket table has primary key as composite of(booking_id,seq), and foreign key booking_id from Booking table.
and it works as foreign key in TicketAllocation table.
How can i define relation in both Ticket and TicketAllocation table so i can use AR relation to get related data.

Hii it you can simply use this
Ticket Model
public function relations()
{
return array(
'ticketToBoooking' => array(self::BELONGS_TO, 'Boooking', 'booking_id'),
);
}
TicketAllocation Model
public function relations()
{
return array(
'ticketAllcationToBooking' => array(self::BELONGS_TO, 'Boooking', 'booking_id'),
);
}

Related

Laravel get column name using child table with eager loading

I want to fetch the data from profile table using a child table of other parent table.
Here is the tables
Profile table
id
profile_name
Transaction table
id
transaction_name
Sub transaction table
id
transaction_id
profile_id
Now i want to get the profile name from transaction model using eager loading . i tried has one Though relationship in transaction model but returning null
Here is my relationship in Transaction model
public function profileName()
{
return $this->hasOneThrough(
Profiler::class,
SubTransaction::class,
'profile_id',
'id',
'id',
'transaction_id',
);
}
Here is where i am trying to fetch from transaction controller
$options = Transaction::with([
'profileName:id,profile_name as profileName',
])
->get();
It returns null because I think you have a little problem about matching between foreign keys and local keys. You could try the following code:
return $this->hasOneThrough(
Profiler::class, //Final model we wish to access
SubTransaction::class, //The name of the intermediate model
'transaction_id', //Foreign key on sub_transaction table
'id', //Foreign key on profile table
'id', //Local key on transaction table
'profile_id', //Local key on sub_transaction table
);
If you have any problem, tell me.

Laravel Eloquent relationships with 3 Table

Laravel 3 Table
table_user
id
name
table_barang
id
iduser
name
statusbarang_id
table_statusbarang
id
name
My code UserModels:
public function BarangModels()
{
return $this->hasMany(BarangModels::class, 'iduser');
}
My code BarangModel :
public function UserModels()
{
return $this->belongsTo(UserModels::class);
}
public function StatusBarangModels()
{
return $this->hasOne(StatusBarangModels::class, 'idstatusbarang');
}
My Code StatusBarangModels :
public function BarangModels()
{
return $this->belongsTo(BarangModels::class);
}
My Code Usercontroller
public function showdetail($id)
{
$value = UserModels::find($id);
return view('user/detailuser', compact('value'));
}
And, I want to select barangmodels (id, name) statusbarangmodels (name)
thank you
First you need to add primary key of BarangModel as foreign key in StatusBarangModels for the relationship that you define in models. After adding key use the following code.
UserModels::with(['BarangModels'=>function($item){
$item->with(['StatusBarangModels'=>function($query){
$query->select('statusbarang_id','name');
}])->select('id','name');
}])->get();
You need to select foreign key in nested relationships so that eloquent can match primary and foreign key in tables.
This will work.
Thank you

Laravel hasManyThrough returning empty array

I need some help regarding hasManyThrough()
user_duty
id
user_id
date
duty_hours
sales_duty
id
user_id
date
total_sales
total_orders
income_table
id
sales_id (this is same as 'id' of sales_duty)
date (same as 'date' of sales_duty)
total_income
total_collection
I can relate sales_duty with income_table using (sales_id,date) these two keys.
I can also connect to sales_duty from user_duty based on (user_id,date)
Now I want to connect to user_duty to income_table
public function user_income()
{
return $this->hasManyThrough('App\IncomeTable','App\SalesTable','id','sales_id','id','id');
}
But its returning empty
According to the details you have provided it should be like this.
public function user_income()
{
return $this->hasManyThrough(
'App\IncomeTable',
'App\SalesTable',
'user_id', // Foreign key on sales_duty table...
'sales_id', // Foreign key on income_table...
'id', // Local key on user_duty table...
'id' // Local key on sales_duty table...
);
}

save one to one relationship. foreign keys in both tables

I have two tables as follow:
CREATE TABLE pets(
id int NOT NULL AUTO_INCREMENT,
user_id int,
any_data varchar(255),
foreign key (user_id) references users(id),
primary key(`id`)
);
CREATE TABLE users(
id int NOT NULL AUTO_INCREMENT,
pet_id int,
any_data varchar(255),
foreign key (pet_id) references pets(id),
primary key(`id`)
);
And my models have the next:
USERS:
public function relatedPet() {
return $this->hasOne("Pet", "pet_id");
}
PETS:
public function relatedUser() {
return $this->belongsTo("User", "user_id ");
}
I want to save an User and relate to an existent pet, but i don't know how to do that:
$user= new User(array("any_data"=>"Hi, this is a test"));
$pet = Pet::find(1);
How can I create the relation between the two objets?
First your users table does not need a pet_id. Drop it. Then
Users Model
public function pet()
{
return $this->hasOne('App\Pet'); // Changed form hasMany to hasOne
}
Pet Model
public function user()
{
return $this->belongsTo('App\User');
}
Now create a new User
$user = \App\User::create($data); // You need to set $fillable property
$pet = \App\Pet::findOrfail($id)
$pet->user()->associate($user);
$pet->save();
Examples:
$user = \App\User::findOrFail($id);
$pet = $user->pet
// Inserting a new user and a pet
$anotherUser = \App\User::create($data);
$anotherPet = new \App\Pet($data);
$anotherUser->pet()->save($anotherPet);
$pet = \App\Pet::findOrFail($id);
$user = $pet->user
// Inserting a new pet, a user and then associating them
$anotherPet = \App\Pet::create($data);
$anotherUser = \App\User::create($data);
$anotherPet->user()->associate($anotherUser);
$anotherPet->save()

Laravel - Many to Many Polymorphic Relation with Extra Fields

How can I define a many to many polymorphic relation with extra fields?
I have three (or more, as it is a polymorphic relation) tables.
tags table: id, name
tagged table: id, tag_id, taggable_id, taggable_type, user_id
posts table: id, record, timestamps
users table: id, name, email
The user_id on the tagged table referes to the users table on column id.
In my Post model I have:
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable','tagged');
}
and in my Tag model I have:
public function posts()
{
return $this->morphedByMany('App\Post', 'taggable','tagged');
}
Then when I am try this in my controller:
$tag = new \App\Tag(
array(
'tag'=>"someTag"
));
$tag->save()
$post = \App\Post::find($id);
$post->tags()->save($tag);
I get Integrity Constraint Violation for not having a user_id:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (hb.tagged, CONSTRAINT tagged_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id)) (SQL: insert into tagged (tag_id, taggable_id, taggable_type) values (26, 2, App\Resource)).
Which is somewhat expected, as I have never had the chance to define or declare the user_id field.
Also, I have tried withPivot() on tags relation as follows, to no avail:
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable','tagged')->withPivot('user_id');
}
Like in the comment: withPivot has nothing to do with saving/creating. If you want to pass additional pivot data when saving, do this:
$post->tags()->save($tag, ['user_id' => $userId]);

Resources