Laravel - Get articles from feeds for one user - laravel

I have three tables:
articles :
id
feed_id
title
feeds :
id
user_id
name
users :
id
name
I want get all articles from feeds for one user, I search the Eloquent Relationships...
Could you help me please?

First, define the relation on User model. Best option for you situation is to use a Has Many Through relation:
public function articles()
{
return $this->hasManyThrough(
'App\Article',
'App\Feed',
'user_id', // Foreign key on feeds table...
'feed_id', // Foreign key on articles table...
'id', // Local key on users table...
'id' // Local key on feeds table...
);
}
Then make a user object and get his articles:
$user = /App/User::with('articles')->find($id);
foreach($user->articles as $article) {
// do whatever you need
}

laravel documentation is always a good start for researching, read about hasManyThrough
https://laravel.com/docs/5.5/eloquent-relationships#has-many-through
don't mind if it is in 5.5, there are no significant differences between them

in model
in Articles.php
public function Feed()
{
return $this->belongsTo('App\Feed');
}
in Feed.php
public function User()
{
return $this->belongsTo('App\User');
}
public function Articles()
{
return $this->hasMany('App\Articles');
}
in User.php
public function Feed()
{
return $this->hasMany('App\Feed');
}
in controller
// To get all articles of user with id = $id
$reports2 = Articles::with(array('Feed'=>function($query)use($id){
$query->with('User');
$query->where('user_id',$id);
}))->orderBy('id', 'desc')
->get();

Related

Laravel get count from model relationship

I have this 3 model.
Author
|id|name|
Post
|id|author_id|
Likes
|id|post_id|
The relationship.
Author
public function post()
{
return $this->hasMany(Post::class, 'author_id', 'id');
}
Post
public function author(){
return $this->belongsTo(Author::class, 'id', 'author_id');
}
public function likes(){
return $this->hasMany(Likes::class, 'post_id', 'id');
}
Likes
public function post()
{
return $this->belongsTo(Post::class, 'id', 'post_id');
}
My problem is, how to list all Authors with total likes from all of his posts.
Using call $authors->posts->likes results an error because posts returns a collection.
Author hasMany posts, and Post hasMany likes.
To achieve all likes from the Author model, you can define a hasManyThrough() relationship :
public function likes()
{
return $this->hasManyThrough(
'App\Likes', // Likes model
'App\Post', // Post model
'author_id', // Foreign key on posts table...
'post_id', // Foreign key on likes table...
'id', // Local key on authors table...
'id' // Local key on posts table...
);
}

get relatinal column HasManyThrough, set in response

i have craete membership that user can purchase one time of get all users with their membership and when they have purchase and when expired i'm confuse with this how to get my table structure is as:
User Model:
id
membership_id
public function membership() {
return $this->belongsTo(Membership::class);
}
Order:
id
user_id
public function item() {
return $this->hasOne(OrderItem::class, 'order_id', '_id');
}
order_item:
order_id
membership_id
created_at
expiration_date
public function membership() {
return $this->belongsTo(Membership::class, 'membership_id', '_id');
}
public function order() {
return $this->belongsTo(Order::class, 'order_id', '_id');
}
membership:
id
name
type
I want get data on time of listing like this how to load relation:
user{
name
email
membership{
name
type
order_item{
expiration_date
created_at
}
}
}
In membership model create this relation.
public function orderitems() {
return $this->hasOne(OrderItem::class, 'membership_id', 'id');
//It's upto you to confirm that whether it is a one-to-one or one-to-many relation
}
Then inside controller you can do something like
User::with('membership.orderitems')->get();
Updated
Alternatively you can create this hasManyThrough relation which will give you all order_items related users. Place this relation inside User Model.
public function items()
{
return $this->hasManyThrough( //please also check hasOneThrough according to your need
'App\OrderItem',
'App\Order',
'user_id', // Foreign key on order table...
'order_id', // Foreign key on order_item table...
'id', // Local key on users table...
'id' // Local key on order table...
);
}

Retrieve related models using hasManyThrough on a pivot table - Laravel 5.7

I'm trying to retrieve related models of the same type on from a pivot table.
I have 2 models, App\Models\User and App\Models\Group and a pivot model App\Pivots\GroupUser
My tables are have the following structure
users
id
groups
id
group_user
id
user_id
group_id
I have currently defined relationships as
In app/Models/User.php
public function groups()
{
return $this->belongsToMany(Group::class)->using(GroupUser::class);
}
In app/Models/Group.php
public function users()
{
return $this->belongsToMany(User::class)->using(GroupUser::class);
}
In app/Pivots/GroupUser.php
public function user()
{
return $this->belongsTo(User::class);
}
public function group()
{
return $this->belongsTo(Group::class);
}
I'm trying to define a relationship in my User class to access all other users that are related by being in the same group. Calling it friends. So far I've tried this:
app/Models/User.php
public function friends()
{
return $this->hasManyThrough(
User::class,
GroupUser::class,
'user_id',
'id'
);
}
But it just ends up returning a collection with only the user I called the relationship from. (same as running collect($this);
I have a solution that does work but is not ideal.
app/Models/User.php
public function friends()
{
$friends = collect();
foreach($this->groups as $group) {
foreach($group->users as $user) {
if($friends->where('id', $user->id)->count() === 0) {
$friends->push($user);
}
}
}
return $friends;
}
Is there a way I can accomplish this using hasManyThrough or some other Eloquent function?
Thanks.
You can't do that using hasManyThrough because there is no foreign key on the users table to relate it to the id of the group_user table. You could try going from the user to their groups to their friends using the existing belongsToMany relations:
app/Models/User.php:
// create a custom attribute accessor
public function getFriendsAttribute()
{
$friends = $this->groups() // query to groups
->with(['users' => function($query) { // eager-load users from groups
$query->where('users.id', '!=', $this->id); // filter out current user, specify users.id to prevent ambiguity
}])->get()
->pluck('users')->flatten(); // massage the collection to get just the users
return $friends;
}
Then when you call $user->friends you will get the collection of users who are in the same groups as the current user.

Using eloquent to query multiple tables

I am using Laravel 5.6. I am trying to query information from the grading_info table but I also want to return the students name and other info from the student_info table. I only want to return records in the grading_info table that are related to the currently logged in teacher. Currently its returning information for all teachers. I know I can add a where clause but I am trying to learn eloquent and was wondering if there was any way to accomplish this?
Teachers and students can have many enteries in the grading_info table and any teacher can grade any student.
I would like to return something like this
{
gradeID,
gradeDate,
gradeInfo
.....
student: {
studentName,
studentPhoneNumber,
studentEmail
......
}
}
users table (only stores teachers, not student)
id
teacher_info
teacherID (linked to id from users table)
student_info
id (auto increment. not relation to the users table)
grading_info
studentID (linked to id from student_info)
teacherID (linked to id from users)
User model
public function grades(){
return $this->hasMany(GradingInfo::class, 'studentID');
}
GradingInfo model
public function teacher(){
return $this->belongsTo(User::class, 'id', 'teacherID');
}
public function student() {
return $this->belongsTo(StudentInfo::class, 'studentID', 'id');
}
StudentInfo model
public function grades() {
return $this->hasMany(SessionInfo::class, 'studentID', 'id');
}
TeacherInfo model
// Nothing in here.
TeacherController
public function getGrades(Request $request)
{
$user = Auth::user(); // This is the teacher
$grades = $user->with('sessions.student')->orderBy('created_at', 'DESC')->get();
return response()->json(['sessions' => $sessions], 200);
}
You have Many to Many relationship between user(teacher) and student(student_info) tables
User Model
public function gradeStudents(){
return $this->belongsToMany(StudentInfo::class, 'grading_info', 'teacherID', 'studentID');
}
public function info(){ //get teacher info
return $this->hasOne(TeacherInfo::class, 'teacherID');
}
StudentInfo model
public function gradeTeachers(){
return $this->belongsToMany(User::class, 'grading_info', 'studentID', 'teacherID');
}
Now Fetch the data (TeacherController)
public function getGrades(Request $request)
{
$user = Auth::user(); // This is the teacher
$students = $user->gradeStudents; // it will return all graded students by logged in teacher
return response()->json(['students' => $students], 200);
}
Here grading_info is a pivot table for Many-To-Many relationship
for details check this https://laravel.com/docs/5.6/eloquent-relationships#many-to-many
Fetch Extra info from pivot table
If you want to add extra info in pivot table (grading_info) then add column (info) in this table and then need to change relationship like this
public function gradeStudents(){
return $this->belongsToMany(StudentInfo::class, 'grading_info', 'teacherID', 'studentID')
->withPivot('info')
->as('grade')
->withTimestamps();
}
Now if you fetch data
$user = Auth::user(); // This is the teacher
$students = $user->gradeStudents;
foreach($students as $student){
print_r($student);
print_r($student->grade->info);
print_r($student->grade->created_at);
}

belongsTo does not work in laravel

In my app I have Users and Tickets.
In the table 'tickets' I have one foreign key, like this:
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
In the model 'Ticket' I have this relationship:
public function owner()
{
return $this->belongsTo('App\User');
}
User model:
public function createdTickets()
{
return $this->hasMany('App\Ticket');
}
By doing this:
dd(\Auth::user()->createdTickets()->get()->toArray());
I get all tickets, no problem here. But when I try to get the owner from the Ticket, it gives me null:
$ticket = \Auth::user()->createdTickets()->first();
dd($ticket->owner); //if I try dd($ticket) it juts fine.
PS: For the record, I have another type of relationship between both model (many to many)
Ticket:
public function followers()
{
return $this->belongsToMany('App\User')->withTimeStamps();
}
User:
public function followingTickets()
{
return $this->belongsToMany('App\Ticket')->withTimeStamps();
}
I got my answer on laracasts forums:
Laracasts
for "belongsTo" relation eloquent uses the method name on the foreign key. I am using owner(), so eloquent was looking for owner_id field.
So I had to do this:
public function owner()
{
return $this->belongsTo('App\User', 'user_id');
}

Resources