How can i get 3 table data in index in laravel? - laravel

I have 3 tables schools, school_Details,ratings
** Schools**
id
name
phone
school
email
status
School details:
-id
school_id
image
status
ratings:
-id
school_id
rating_value
status
both rating &school details have only one row for one school_id.
Now how can i get all details from all 3 tables in index from schoolController

Use Laravel Relationship.
In Schools Model add this.
public function schoolDetails()
{
return $this->hasOne('App\SchoolDetails');
}
public function ratings()
{
return $this->hasOne('App\Ratings');
}
In School Details Model add this.
public function school()
{
return $this->belongsTo('App\School');
}
In Ratings Model add this.
public function school()
{
return $this->belongsTo('App\School');
}
In School Controller
public function index()
{
$schools = Schools::with('schoolDetails')
->with(ratings)
->get();
return $schools;
}
Can you try this,

This is a pretty wide question. It would help to show what you've tried so far. The answer is to create one to many relationships from schools to details and ratings.
And then call those relations within the base school object from your index method. You can even eager load these for one simple and clean pull from the database.
To clarify, from your School model:
public function ratings()
{
return $this->hasMany('App\Rating');
}
And same thing for your school details. Then, to eager load in your index method:
$schools= App\School::with(['ratings', 'details'])->get();
Then your school object has all you've asked for:
$school->ratings->status
etc.

Related

Laravel Eloquent Relationship by Models

I have a table called "categories" and there is a 3 table needed the id of categories
the 3 tables needed a categories id is "activies", "stories", "news" i really want to know how to fix this issue the stories and news table is running well im using php tinker to see if the relationship is running and the table activities it give me a null value, inside the activities table i`d input same category_id in the table of activities it gives always a null value given in php tinker
Models
Category.php
public function stories()
{
return $this->hasMany(Story::class);
}
public function news()
{
return $this->hasMany(Newy::class);
}
public function activites()
{
return $this->hasMany(Activity::class);
}
Activity.php
public function category()
{
return $this->belongsToMany(Category::class, 'category_id');
}
If you are using hasMany in your Category Model, the opposite relationship in your Activity model should be belongsTo() and not belongsToMany()
public function category()
{
return $this->belongsTo(Category::class);
}
You can read more in the documentation here

How to create relationship in Laravel 5 which will collect records of own model mentioned in pivot table?

I have 3 tables users, companies and pivot table with user_id, company_id.
I can't get users, which belongs to my company inside User model.
Tried like
belongsToMany('App\User','companies_users','company_id','user_id' );
but I get relation with wrong users.
Since you are having a belongsToMany relationship between the User and Company, the User belongs to more than one Company. To get users of the companies of a particular User will not be straight forward. If you are sure that is exactly what you want, then do this:
//inside the User model
public function companies()
{
return $this->belongsToMany('Company');
}
//inside the User model
public function companiesusers()
{
$users= new Illuminate\Database\Eloquent\Collection;
foreach($this->companies as $company)
{
$users = $users->merge($company->users->get());
}
return $users->unique();
}
//inside the Company model
public function users()
{
return $this->belongsToMany('User');
}
Then you can get a user's companiesusers like so:
User::first()->companiesusers();

eloquent multi table query and relationships

I am new to this so bear with me.
I have 4 tables (users, scores, scorecards, courses) and I need to bring into a view info from all of these tables.
Here are the relationships:
Scores model
public function user(){
return $this->belongsTo('App\User');
}
public function scorecard(){
return $this->belongsTo('App\Scorecard');
}
public function course() {
return $this->belongsTo('App\Course');
}
Course model
public function club(){
return $this->belongsTo('App\Club');
}
public function scorecard(){
return $this->hasMany('App\Scorecard');
}
public function score() {
return $this->hasMany('App\Score');
}
Scorecard model
public function course(){
return $this->belongsTo('App\Course');
}
public function club(){
return $this->belongsTo('App\Club');
}
In my controller I get the scores id from a dropdown in the request. I need to essentially get the following info:
the scores record which is easy as i have the score id.
use the scorecard_id from the scores table to get the scorecard record from the scorecards table
grab the course info from the courses table using the course_id thats in the scorecards table.
You can eager load the relations using dot . as scorecard.course and it will load both scorecard and course.
$score = Score::with('scorecard.course')->find($id);
and then you can access corresponding attributes as:
$score->scorecard;
$score->scorecard->course;
if $id is the scores id from a dropdown,
$score=Score::with('scorecard','scorecard.course')->where(['id'=$id])->first();
then,
print_r($score);
gives the scores record.
print_r($score->scorecard);
gives the scorecard record.
print_r($score->scorecard->course);
gives the courses record.

I can't make some Eloquent relations to work

Let me first explain the relations of my table, and then I will explain what I cannot do.
So, I have an entity called "Company" it has many "Incomes" which has many "IncomeUnitSale" which has one "IncomeUnitSaleUnitPrice"
Company 1->* Income 1->* IncomeUnitSale 1->1 IncomeUnitSaleUnitPrice
Models:
Company Model
public function Income(){
return $this->hasMany('App\Income');
}
Income Model (table has "company_id")
public function Company(){
return $this->belongsTo('App\Company');
}
public function IncomeUnitSale(){
return $this->hasMany('App\IncomeUnitSale');
}
IncomeUnitSale Model (table has "income_id")
public function Income(){
return $this->belongsTo('App\Income');
}
public function IncomeUnitSaleUnitPrice(){
return $this->hasOne('App\IncomeUnitSaleUnitPrice');
}
IncomeUnitSaleUnitPrice (table has "income_unit_sale_id")
public function IncomeUnitSale(){
return $this->belongsTo('App\IncomeUnitSale');
}
What I am trying to do is the following:
$company = Company::where("id","=",1)->first();
$company->Income->IncomeUnitSale->IncomeUnitSaleUnitPrice
But It says its null, it works till $company->Income->IncomeUnitSale but after that doest't show any relation.
Can somebody please tell me what I am doing wrong?
Thank you!
hasMany relationships will always return an Eloquent Collection object. If there are no related records, it will just be an empty Collection. hasOne and belongsTo relationships will always return either the related Model, or null if there is no related model.
Because some of your relationships are hasMany, you have to iterate the returned Collection to be able to go further. So, instead of $company->Income->IncomeUnitSale->IncomeUnitSaleUnitPrice, you have to:
foreach($company->Income as $income) {
foreach($income->IncomeUnitSale as $sale) {
echo $sale->IncomeUnitSaleUnitPrice->price;
}
}

Laravel 5.1 hasManyThrough Pivot table

I have model many to many relation like. I want to relate State and Category through pivot table CategoryNews.
Category model
class Category extends Model
{
public function news() {
return $this->belongsToMany('App\News');
}
}
News model
class News extends Model
{
public function categories()
{
return $this->belongsToMany('App\Category');
}
public function state()
{
return $this->belongsTo('App\State');
}
}
and the State model
class State extends Model
{
public function news() {
return $this->hasMany('App\News');
}
}
I want to select the news related to the state where cat_type=2(from category table)
i tried
$slide_news = State::whereHas('news.categories',function($query){ $query->where('categories.cat_type',2);})
->with(array('news'=>function($query){
$query->orderBy('created_at', 'desc');}
))->where('id',$id)->first();
but the cat_type filter is not working. I also tried hasManyThrough but i don't know how to implement it with Pivot Table
Please help
There is a Laravel 5.5 composer package that can perform multi-level relationships (deep)
Package:
https://github.com/staudenmeir/eloquent-has-many-deep
Example:
User → belongs to many → Role → belongs to many → Permission
class User extends Model
{
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function permissions()
{
return $this->hasManyDeep(
'App\Permission',
['role_user', 'App\Role', 'permission_role'], // Pivot tables/models starting from the Parent, which is the User
);
}
}
Example if foreign keys need to be defined:
https://github.com/staudenmeir/eloquent-has-many-deep/issues/7#issuecomment-431477943
To the moderators:
DO NOT DELETE MY ANSWER
It took me two god damn days to solve this issue, and I was so happy i found the solution that i want to let the world know
Notice that my answer was upvoted, yet you deleted it.
The question's title is regarding: hasManyThrough Pivot table for Laravel, and my answer gives just that, a solution to perform hasManyThrough equivalent on Pivot Tables
The question was 3 years old, and let's admit no one wants a solution specific to the question, because we've all got our own.
If I were you, I'd prefer a generic answer.

Resources