Laravel Relationship through sub table - php

I'm trying to implement a blog type website where the user can rate the posts. So the relationship is like this:
Blog -> blog_links; To Many fk = blog_id
User -> blog_links; To Many fk = user_id
I've tried these solutions and each time get a different error:
User::hasManyThrough(Blog::class, BlogLink::class);
That didn't work, so I tried query scope:
scopeWithLinksAndResorts($query) {
return $query->with(['resorts' => function($q) {
$q->ordered()->withLinks();
}]);
}
That doesn't seem to return any results. So I'm not sure what I'm doing wrong here. And here's a table example:
blogs
id Title Text
1 Test This is a test blog
users
id email
1 test#test.com
blog_links
id blog_id user_id rating
1 1 1 4
Now from this I want to get the blogs the user has rated and their rating. But as I said I get no results. Anyone able to help?

In your User model define the blog's relation
/**
*
*/
public function blogs()
{
return $this->belongsToMany('App\Blog', 'blog_links', 'user_id', 'blog_id')->withPivot('rating');
}
Then in your Blog model define the user's relation
/**
*
*/
public function users()
{
return $this->belongsToMany('App\User', 'blog_links','blog_id', 'user_id');
}
To get all users with their blogs and rating you can do \App\User::with('blogs')->get()
I'm not sure if this is what you want but hope it helps.

Related

Laravel 5.5 HasManyThrough Relationship

I have the following database:
teams
-----
id
user_id
users
-----
id
pages
-----
id
user_id
team_id -> (nullable)
So a User can create a Team, and create a Page
Currently, I have the following relationships setup (replace with $this)
teams_owned() -> $user->hasMany(Team::class); // Teams a user owns
pages() -> $user->hasMany(Page::class); // Page a user created
user() -> $team->belongsTo(User::class); // User who created team
user() -> $page->belongsTo(User::class); // User who created the Page
However, a User can join a team by creating a Page for that team. In this case the pages table will fill in the team_id. Where a page is created and is not for a team, the team_id value will be null
I wanted to add a relationship for User to get the Teams joined. As explained above, you are part of Team if you have created a Page for it.
I have tried the following:
public function teams_joined()
{
return $this->hasManyThrough(Team::class, FundraisingPage::class);
}
I'm not sure if I should be using a HasManyThrough in this situation
As a backup I have the following:
public function teams_joined()
{
$uniqueTeamIds = $this->pages()->onlyForTeams()->get()->pluck('id')->unique();
return Team::whereIn('id', $uniqueTeamIds)->get();
}
where onlyForTeams() is defined on Page as
public function scopeOnlyForTeams($query) {
return $query->whereNotNull('team_id');
}
But I wanted to use a proper relationship so was wondering if I should be using HasManyThrough or something else for this situation.
Use a BelongsToMany relationship:
public function teams_joined()
{
return $this->belongsToMany(Team::class, 'pages');
}

How to update a row in DB without overwriting the existing data with laravel 5.2

I have a table which stores the user's interested topics along with the user id and topic id. The table will look like
Topic name topic id User-id
Sports 1 1
Education 2 3
Family 3 1
What i want to do is when a new user , say user-id '3' adds his interest as topic sports , then the first row should look like this
Topic name topic id User-id
Sports 1 1,3
When i try to update it overwrites the whole column like
Topic name topic id User-id
Sports 1 3
What is the right approach to do this ?
The right approach is to use Many-To-Many relationship:
Tables:
users (id, ....);
topics (id, ....);
topic_user (topic_id, user_id);
PHP:
class User extends Model {
public function topics() {
return $this->belongsToMany('App\Topic');
}
}
and :
class Topic extends Model {
public function users() {
return $this->belongsToMany('App\User');
}
}
For more details please refer to https://laravel.com/docs/5.2/eloquent-relationships.
I hope this will help.

Laravel relationship to show all posts by authors that they follow

Can normally figure these relationships out but stumped on this one.
I have a basic blog platform that allows user to sign up and post blog posts.
Users can also follow other users.
I am trying to make a view where I can see all of the blog posts by the authors that I follow
I have the normal users table, and then a blog posts table which contains the user_id of the creator.
For followers, I then have a pivot table called followers which has user_id and follower_id.
This is my basic line to get all posts:
$posts = Post::orderBy('created_at', 'DESC')->get();
How can I change that so it only shows the posts where there post user_id is a field that matches in the followers table?
Thanks.
You may try something like this:
App\User Model:
public function favoriteAuthors()
{
return $this->belongsToMany(
User::class, // as Author
'followers', // pivot table
'follower_id', // as follower_id
'user_id', // as author_id
);
}
public function posts()
{
return $this
->hasMany(Post::class, 'user_id', 'id')
->orderBy('created_at', 'DESC');
}
Then load all posts of your favorite authors:
$posts = User::with('favoriteAuthors.posts')->find(auth()->user()->id);
Also you can use something like this:
if($me = auth()->user()) {
$me->load(['favoriteAuthors.posts']);
}
Now the $me will contain users that you follw and each users will contain their posts.

Laravel 5 Eloquent select items in Table 1 that dont have relation in table 2 when table 2 id = x

I am trying to find a method similar to has() that would allow me to do following:
Select all users from users that doesntHave link with subscriptions table when subscriptions.id = x
user might have a link with subscription.id = 1, subscription.id = 2 but not 3. So i want to exclude users that already have a link with subscription table when subscription entry under question has id of X
users table:
user1 has access to subscr1 and subscr2
user2 has no links
user3 has link to subscr1
subscr table:
subscr1
subscr2
subscr3
so when i want to get a list of users that dont have a link with item subscr3 from subscr table I would expect to see user2 and user3
I think you could get this via a relation in this way:
// User model
public function subscriptions()
{
return $this->belongsToMany('App\Subscription');
}
public function hasSubscription(Subscription $subscription)
{
return (bool)$this->subscriptions()
->where('subscription_id', $subscription->id)
->first();
}
Usage:
if($user->hasSubscription($subscription)) {
// User has subscription
}
You may use whereDoesntHave, assumed you've setup relation like this in your App\User model:
public function subscriptions()
{
return $this->belongsToMany('App\Subscription');
}
Then you can use something like this:
$subscriptionId = 3;
$users = User::whereDoesntHave('subscriptions', function($q) use($subscriptionId) {
$q->where('subscriptions.id', $subscriptionId);
})
->get();

Laravel 5 insert pivot table with attributes

I've been learning laravel for a few days now and I was hoping you guy's could help me.
I have the following table structure:
users
------
id
companies
------
id
company_user
------
company_id
user_id
owner
My User and Company models have functions specified like this:
User Model
public function companies() {
return $this->belongsToMany('App\Company', 'company_user', 'company_id', 'user_id')->withPivot('owner');
}
Company Model
public function users() {
return $this->belongsToMany('App\User', 'company_user', 'company_id', 'user_id')->withPivot('owner');
}
For example when I save a company to a user like this:
User::find(1)->companies()->save(\App\Company::find(1));
The pivot table gets filled nicely, but the owner column doesn't get filled.
I can't find many online how to fill this column. Hope you guys can help me?
Thanks in advance!
You can pass additional data as second argument to save():
User::find(1)->companies()->save(\App\Company::find(1), ['owner' => 'foo']);

Categories