how to convert joins query to laravel eloquent query - php

I have query bulider's query like this
$schedule = DB::table('users')
->join('tblHomeCourts','users.homeCourtId','tblHomeCourts.homeCourtId')
->join('tblUserHomeCourts','tblUserHomeCourts.userId','users.userId')
->join('tblSchedules','tblUserHomeCourts.userHomeCourtId','tblSchedules.userHomeCourtId')
->select('tblHomeCourts.homeCourtName', 'tblHomeCourts.address','tblSchedules.timeFrom','tblSchedules.timeTo','tblSchedules.duration','tblSchedules.scheduleStatus','users.firstName','users.lastName','users.profilePic','users.userId')
->where(['tblSchedules.scheduleStatus'=> 0,
])->where('timeFrom','>',$request->currentTime)
->where('timeTo','>',$request->currentTime)
->where('tblUserHomeCourts.homeCourtId',$homeCourtId)
->get();
Now, I want to convert this into proper eloquent query using eloquent relationship I'm fully messed up with relationships can somebody please help me to find out the solution?
thanks :)

To achieve this we have to define relationships among the related table for the first place. Then we need to load the joint table using the with method.
For example you User model should look like this:
class User extends Model{
protected $table = 'users';
public function homeCourt(){
//Many to one relation between user and homeCourt
return $this->belongsTo(HomeCourt::class, 'homeCourtId', 'homeCourtId');
}
public function userHomeCourts(){
//One to many relation between user nad userHomeCourt
return $this->hasMany(UserHomeCourts::class, 'userId', 'userId');
}
}
Your HomeCourt model should look like:
public class HomeCourt extends Model{
protected $table = 'tblHomeCourts';
public function user(){
//One to many relation between homeCourt and user
return $this->hasMany(User::class, 'homeCourtId', 'homeCourtId');
}
}
Your UserHomeCourt model should look like:
public class UserHomeCourt extends Model{
protected $table = 'tblUserHomeCourts'
public function user(){
//Many to one relation between userHomeCourts and users
return $this->belongsTo(User::class, 'userId', 'userId');
}
public function schedules(){
//One to many relation between userHomeCourts and schedule
return $this->hasMany(Schedule::class, 'userHomeCourtId', 'userHomeCourtId');
}
}
Your Schedule model should look like:
public function Schedule extends Model{
protected $table = 'tblSchedules';
public function userHomeCourt(){
//Many to one relation between schedule and userHomeCourts
return $this->belongsTo(UserHomeCourt::class, 'userHomeCourtId', 'userHomeCourtId');
}
}
Now you are ready to build your query. This query is bit different than the query you have built using query builder. Besides, the output of laravel eloquent query is also different. You have to adjust that result with you view:
You can query like this:
$users = User::with('homeCourt', 'userHomeCourts.schedule')->where('timeTo', '>', ,$request->currentTime)->get();
This query is just an example, you have to define it according to your requirement. Here, the parameters of with methods are the methods name of that users table relation with other tables. This is how it works.
You can read more here: https://laravel.com/docs/5.4/eloquent-relationships

Related

How to make relationship between three table in laravel eloquent

I have three tables, Sections,Questions and options.
Each Section has many questions and each question has many options.
How can I fetch data from this tables related to each other?
Section model relationship with Question model
class Section extends Model
{
use HasFactory;
protected $primaryKey='sectionid';
public function questions(){
return $this->hasMany(Question::class,'sectionid')->orderBy('order');
}
}
Question model relationship with Option model:
class Question extends Model
{
use HasFactory;
protected $primaryKey='questionid';
public $timestamps = true;
public function options(){
return $this->hasMany(Option::class,'questionid');
}
}
my query:
$data=Section::with('questions')
->where('formid',$formId)
->orderBy('sectionid')
->get()
->toJson();
It returns this:
I want each questions member contains options array related to it.
You can use nested relation in with like below.So it will fetch question options also
$data=Section::with(['questions','questions.options'])
->where('formid',$formId)
->orderBy('sectionid')
->get()
->toJson();

Laravel Many To Many Pivot Table different Database

Laravel 5.5
I've got two models, User and Conversation
User to Conversations is a many to many relationship (both ways).
My table structure is as follows:
conversation is on database_1
conversation_user is on database_1
user is on database_2
Inside App\Conversation.php:
protected $connection = 'database_1';
protected $table = 'conversations';
public function users()
{
return $this->belongsToMany("App\User");
}
Inside App\User.php:
protected $connection = 'database_2';
protected $table = 'users';
public function conversations()
{
return $this->belongsToMany("App\Conversation");
}
All of this is on the same server but is there a way to have this working or not ?
When querying the relationship on Conversation to get users, it's looking for database_2.conversation_user instead of database_1.conversation_user
So in essence, I need to say that the Pivot table is located in database_1, is there a way to do this?
One way to work around this is using the query builder to create the relationship. In your User model try:
public function conversations()
{
return DB::connection('db1_connection_name')->table('conversation_user')->where('user_id', $this->id)->get();
}
Apparently you can prefix the connection in a relationship also:
public function conversations() {
return $this->belongsToMany(User::class, env('DB_CONNECTION_1').'.conversation_user', 'user_id', 'conversation_id');
}

Laravel 5 – get particular many to many relation based on model and related model ID

I've got Tag and Attendee Eloquent models, they are in many-to-many relation. Pivot table has also two more attributes – value_int and value_string. My Attendee model looks like this:
class Attendee extends Model
{
public $timestamps = false;
protected $fillable = [
'event_id'
];
public function tags() {
return $this->belongsToMany('App\Models\Tag', 'attendee_tag', 'attendee_id', 'tag_id')
->withPivot(['value_string', 'value_int']);
}
public function scoreTagValue($tag_id) {
return $this->tags->where('tag_id', '=', $tag_id)->first();
}
}
What I want is to obtain pivot values based on Attendee model and variable tag_id, so I've written scoreTagValue function, but it always returns null and I don't know why :( I'm calling it this way:
$attendee->scoreTagValue($tag_id). Thanks for your help :)
You need to access the relation, not the property:
public function scoreTagValue($tag_id) {
return $this->tags()->where('tag_id', '=', $tag_id)->first();
}
Also, according to the docs, withPivot() does not take an array, so:
->withPivot('value_string', 'value_int');

How to return one property of a belongsTo model with the child model in Laravel resource controller

I'm using Laravel as a REST API for a SPA. I have a relationship where families have multiple contributions. The contributions table has a foreign key reference to family's id. I can call on the contributions route with the hasMany/belongsTo set up, and every contribution gets the entire family model it belongs to. But I don't need all that data, I just need a single field from the family table (not the id, but a different field) with each contribution.
Here are my models and resource controller:
class Family extends Eloquent {
protected $table = 'families';
// relationships
public function contributions() {
return $this->hasMany('Contribution');
}
}
class Contribution extends Eloquent {
protected $table = 'contributions';
// relationships
public function family() {
return $this->belongsTo('Family');
}
public function other_field() {
return $this->belongsTo('Family')->select('other_field');
}
}
class ContributionController extends BaseController {
public function index()
{
// works - but returns the entire family with every contribution
$contributions = Contribution::with('family')->get();
// returns other_field == null with every contribution
$contributions = Contribution::with('other_field')->get();
return Response::json($contributions->toArray(),
200);
}
Where am I going wrong with selecting this single field from the belongsTo relationship?
You can use query constraints on the relationship if you use eager loading.
Family::with(['contributions', function($query)
{
$query->select('column');
}])->get();

Laravel Eloquent Joins

I have below query in core php:
SELECT DISTINCT device_tocken FROM push_details JOIN users ON users.id=push_details.user_id
I have to integrate it in laravel 4
Application already have User extends Eloquent class
I created Push_details class as below
class Push_details extends Eloquent {
public $table = 'push_details';
public function User() {
return $this->hasMany('\User','id');
}
}
Table : users
Primary key : id
Table: push_details
Primary key: id
Foreign key: user_id belongsTo('users.id');
But i m not able to get expected result.
One more thing i didn't write anything in User's model yet.
Only way to join table is.. to join it, as Eloquent relations don't work using joins but separate queries with WHERE IN clauses. So this will do:
DB::table('push_details')
->select('device_tocken')
->distinct()
->join('users','users.id','=','push_details.user_id')
->get();
Above will return array of stdObject's so or if you need Eloquent Collection with Eloquent models as a result replace DB::table('push_details')->select... with PushDetails::select...
Now, correct your relations, as they are wrong:
// PushDetails model (as previously stated, I suggest renaming it to StudlyCase)
public function user() {
return $this->belongsTo('\User','user_id'); // user_id is may be omitted here
}
// User model
public function pushDetails() {
return $this->hasMany('\PushDetails','user_id'); // user_id is may be omitted here as well
}
In your User model, you need to link back to the PushDetails model, like so
class User extends Eloquent {
public function push_details() {
return $this->belongsTo('PushDetails');
}
}
Use CamelCase for Class names, because laravel has several functions, in which CamelCase are changed to snake_case
Change
public function User() {
return $this->hasMany('\User','id');
}
to
public function users() {
return $this->hasMany('User');
}
See the docs 'Eloquent ORM' for more...

Categories