Laravel 5.1 hasManyThrough Pivot table - laravel-5

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.

Related

Using Pivot relations in laravel

I've the following tables:
1.institute_codes
id
institute_id
course_id
code
1
3
45
ABCD
2.code_claims
id
code_id
user_id
approved
1
1
4
0
The institute_codes and code_claims are pivot tables. I want to retrieve users details based on the user_id column in code_claims and the course information which corresponds to the used code(code_id in code_claims table).
I've the following relationships till now:
class InstituteCode extends Pivot
{
use HasFactory;
protected $table = ['institute_codes'];
public function users()
{
return $this->belongsToMany(User::class, 'code_claims', 'code_id');
}
}
class User extends Model
{
public function codes()
{
return $this->belongsToMany(InstituteCode::class, 'code_claims');
}
}
Any help would be appreciated. Thanks.
So what exactly is your question here? :)
Your relationships are all messed up. I would read into the Laravel documentation first on relationships.
A basic has many / belongs to relationship is important, but also this one might be very interesting in your situation:
https://laravel.com/docs/9.x/eloquent-relationships#has-many-through
Also take note of the foreign key conventions below it.
One important tip is that the BelongsTo relation should always go in the model of the table with the foreign key (f.e. user_id). This way you can not go wrong.

How can i get 3 table data in index in 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.

Laravel multiple hasmany relation limit issue

I have 3 collection pages,posts,comments and relation is
pages => hasmany => posts => hasmany =>comments
pages model relation
public function posts()
{
return $this->hasMany('App\Models\PostsModel', 'page_id');
}
posts model relation
public function comments()
{
return $this->hasMany('App\Models\CommentsModel', 'post_id')->limit(10);
}
Query
PagesModel::with('posts.comments')->get();
it supposes to take all page posts and 10 comments for each post,
but it skips results, Many posts have multiple comments but unable to get comments.
Any solution or a better approach. Thanks
There is no native support for this in Laravel.
I created a package for it: https://github.com/staudenmeir/eloquent-eager-limit
Use the HasEagerLimit trait in both the parent and the related model.
class PostsModel extends Model {
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}
class CommentsModel extends Model {
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}
Then you can apply ->limit(10) to your relationship.
Its a common question for which there is no easy answer. Read https://softonsofa.com/tweaking-eloquent-relations-how-to-get-n-related-models-per-parent/ for an explanation

Laravel: What's the best way to delete a row in a pivot table?

I have 3 models inside a Laravel application:
User
Question
Alternative
Some model relations:
Question can have many Alternative.
Alternative belongs to one Question
There's a pivot table which stores an answer by an user. It stores the user_id and the alternative_id.
In the pivot table, how can I delete all answers from a specific Question? (I have the question_id)
You can use detach as well sync method but you have to define relationships first in your models e.g
public class Question extends Model {
public function alternatives() {
return $this->hasMany(Alternative::class);
}
}
public class Alternative extends Model {
public function users() {
return $this->belongsToMany(User::class);
}
}
and than
$question = Question::findOrFail('question_id');
$question->alternative()->user()->sync();
or
$question->alternative()->user()->detach();

Eloquent many to many self/meta relationship $this->hasMany($this)

So I am working on a project in Laravel 4, and I am wondering how to do a many to many relationship on a single Model. I think comments should be able to belong to other comments (replies) Or at the very least replies should be able to have many replies.
I think that the way I would build the model would be:
Class Comment extends Eloquent {
public function comments() {
// assuming my comments table has an $id column and a second $comment_id table
// do I even need to specify the column name?
return $this->hasMany('Comment', 'comment_id');
}
public function comment() {
return $this->belongsTo('Comment');
}
}
Where can I look for more documentation about this, or what is the Laravel way to achieve what I am trying to achieve?

Resources