Laravel - Has Relationship Through - php

Let's say I have three tables:
1. Server
-------
id
name
2. Player
-------
id
name
ServerId
3. Activity
-------
id
PlayerId
action
time
How would I use Laravel's hasManyThrough to able to get a list of activity from a server's players like so $system->activity?

You can use it as follows:
// this should be inside your Server model.
public function activities()
{
return $this->hasManyThrough(
Player::class,
Activity::class,
'PlayerId', // Foreign key on activities table...
'ServerId', // Foreign key on players table...
'id', // Local key on servers table...
'id' // Local key on activities table...
);
}
This will give you all the server activities through the player.

Related

Check if given date is available from multiple table

I am working on online reservation system where customer will search for room available with time and number of people. My database table looks like this:
Table: Property
id
property_name
property_number
1
abc property
AB-123
2
def property
DF-343
property_number is unique field
Table: Rooms
id
Room Name
Capacity
property_number
1
Room one
150
AB-123
1
Room two
500
AB-123
2
Room one
500
DF-343
property_number is foreign key from table property
Table: Booking
id
property_number
room_id
book_status
book_start
book_end
1
AB-123
1
active
2021-06-06 10:00:00
2021-06-06 18:00:00
property_number is foreign key from table property
room_d is foreign key from table Room
book_status : completed, pending, running, cancelled. If booking status is completed or cancelled than user should be able to book.
User Search Field
Reservation Date
Reservation Start Time
Reservation End Time
Total no of People
User Submits Specific Property Number
Solution Tried
$property = Property:::where('status','active')->where('property_number',$property_number)->firstOrFail();
$bookings = $property->bookings()
->whereBetween('event_date_start',[$event_start,$event_end])
->orWhereBetween('event_date_end',[$event_start,$event_end])
->orWhere( function ( $query ) use ($event_start,$event_end) {
$query->where('event_date_start' , '<', $event_start)->where('event_date_end','>',$event_end);
})
->get();
Model Structure
Table: **Property**
Class Property extends Model {
public function bookings(){
return $this->hasMany(Bookings::class,'property_number','property_number');
}
public function rooms(){
return $this->hasMany(Rooms::class,'property_number','property_number');
}
}
Table: **Rooms**
Class Rooms extends Model {
public function property(){
return $this->belongsTo(Property::class,'property_number','property_number');
}
public function bookings(){
return $this->hasMany(Bookings::class,'room_id');
}
}
Table: **Bookings**
Class Bookings extends Model {
}
This way it checks only property not every room associated with the property.
How to check if any room is available for booking for provided property.*

relation function in models using laravel

I have 3 tables.one is user,second is event and third is eventParticipants.Here i have 3 type of users. one is organizer its status is 1,second is participant its status is 2,third is subparti which organizer and particiant can create and their status is 3.when participant register a event it stores in a eventParticipant table.Also if participant registering event by his participant it also save on the same eventParticipant table.Now my problem comes in the part of listing this registeration in participant dashboard.Here i need to list both participant and his subparti registration detail.But i cnoont get the whole data.I listed my tabel structure below:
1.user
id name email status createdBy
1 A AA 2 0
2 A1 AA1 3 1
3 A2 AA2 3 2
2.EventPArticipants
id eventid eventowner name email
25 18 A AA
27 14 A1 AA1
22 17 A2 AA2
when i am listing in the participant home.blade.php i need:
Name event date action
A Event1 04/05/2020 show
A1 Event2 04/08/2020 show
A2 Event3 04/05/2020 show
here i used model relation but i dont get subpartis.
eventPArticipants.php
public function active(){
return $this->hasMany('App\Models\EventParticipants', 'email', 'email');
}
I dont know what is eventowner, is the the user_id ??? if its the user_id then
use hasManyThrough like this
public function partis(){
return $this->hasManyThrough ('App\Models\Event',
'App\Models\EventParticipants',
'eventowner' or user_id,
'id', // Foreign key on Event table...
'id', // Local key on user table...
'id' // Local key on EventParticipants
);
}
pull the data like This in your controller
$data = User::with('partis')
->where('additional logic')
->get();
You can use callback as well... make Sure Your pivot table (EventPArticipants) is well
By this you can get exact events of the user

How do I create conditional relationship in Laravel eloquent on Comma Separated Column

I have 4 tables vendors, project,project_quotas and project_vendors
Table Structures:
vendors: id (Primary), name, email
project: id (Primary), name, status
project_quotas: quota_id (Primary), project_id (Foreign Key), quota_name, description
project_vendors: pv_id (Primary), project_id(Foreign Key), vendor_id, spec_quota_ids(comma separated, Foreign Keys), description
Lets Say For project_id = 1
I want to fetch All Project Quotas and their Project Vendors
here is Raw query I have created to get this data:
SELECT
pq.id as pq_id, pq.project_id as project_id, pq.name as pq_name, pv.id as pv_id, pv.vendor_id as pv_vendor_id, pv.spec_quota_ids as quotas
FROM `project_quotas` pq
LEFT JOIN
project_vendors pv ON pv.project_id = 1 AND find_in_set(pq.id, spec_quota_ids) > 0
WHERE pq.project_id = 1
GROUP BY pv.vendor_id, find_in_set(pq.id, spec_quota_ids)
Order BY pq.id
Here is the output
The only issue is that I want this query to Run Eloquent way.
I have ProjectQuota, ProjectVendors Model
I want something like
$data = ProjectQuota::where('project_id', '=', '1')->with('projectVendors', 'projectVendors.Source')->get();
I don't know how can I create a conditional hasManyrelationship in eloquent, will appreciate the help.
I this is the way to do this.
if($this->project_id===2) {
return $this->belongsTo(Foo::class);
}
if($this->project_id===3) {
return $this->belongsTo(Bar::class);
}

Laravel References 2e en 3th level

I have 3 tables.
Table news (hasMany Writers)
id
name
Table Writers (hasMany News and BelongsTo Country)
id
Name
country_id
Table Countries (hasMany Writers)
id
name
Now I want to display this in a view:
Name(news), Name(Writer), Name(Country)
I only can display:
Name(news), Name(Writer), country_id
How do I display the country name?
In your TableWriter model you should have a function 'country'.
public function country() {
return $this->belongsTo('TableWriter');
}
The the country_id should be the id of the country and you can do $tableWriter->country()->name where $tablewriter is an instance of your TableWriter.
So with the above in app/TableWriter.php you should be able do do something like:
$tableWriter = AppName\TableWriter::first();
echo $tableWriter->country()->name;
This should echo the counter name of the first TableWriter.

Count Relational Table Rows

I'm trying to count the number of rows in a relational table many to many, but always returns the wrong value. When it is 1, always returns 2.
PS: All models and foreign keys in mysql are configured correctly.
Comments Table:
id | name
10 Comment Test
Users Table:
id | name
20 User Test
Likes (Comment/User) Many to Many:
user_id | comment_id
20 10
Code:
$criteria = new CDbCriteria;
$criteria->select='*, COUNT(likes.id) AS count_likes'; // I believe the error is in the use of COUNT (likes.id).
$criteria->with=array('likes'=>array('on'=>'user_id=20'));
$model = Comments::model()->findByPk($_GET['id'], $criteria);
// Return Wrong Value
echo $model->count_likes; // Return 2 where should be 1. (I need to use this case)
echo count($model->likes); // Return right value 1.
You should use Statistical Query, e.g. :
In your Comments model :
public function relations()
{
return array(
// ...
// I assume your relation table's name is "likes"
'likes'=>array(self::MANY_MANY, 'Users', 'likes(comment_id, user_id)'),
'likesCount'=>array(self::STAT, 'Users', 'likes(comment_id, user_id)'),
// ...
);
}
Are you planning on selecting from the LIKES table and group by them by their userid and comment id?
If so, you can use GROUP BY
Please take a look at the SQLFiddle here
http://sqlfiddle.com/#!2/bc29b8/1/0
SELECT uid, cid, COUNT(likes.cid) FROM likes GROUP BY uid, cid

Categories