get relatinal column HasManyThrough, set in response - laravel

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...
);
}

Related

Laravel hasOneThrough - Laravel relationships

I really need help with the following! I am trying to understand how hasOneThrough works
Users table:
id | belongs_to (id of the company)
Companies Table:
id | country_id
Countries table:
id
So I would like to know the country ID of a user through the Company... in User model I am trying the following:
public function country() {
return $this->hasOneThrough(
'App\Countries',
'App\Companies',
'country_id', // the name of the foreign key on the intermediate model...
'id', // is the name of the foreign key on the final model...
'belongs_to', // is the local key...
'id' // is the local key of the intermediate model...
);
}
Also tried
public function country() {
return $this->hasOneThrough(
'App\Countries',
'App\Companies',
'country_id', // the name of the foreign key on the intermediate model...
'belongs_to', // is the name of the foreign key on the final model...
'id', // is the local key...
'id' // is the local key of the intermediate model...
);
}
But always get NULL as result
As mentioned in the comments, hasOneThrough isn't really meant to belongsTo relationships as you can get the model you're after by simply chaining the relationships together:
$user->company->country;
That being said, this should be the relationship that you want:
public function country()
{
return $this->hasOneThrough(
Countries::class, Companies::class, 'id', 'id', 'belongs_to', 'country_id'
);
}

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.

Laravel - Get articles from feeds for one user

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();

Eloquent Relationship with Laravel 5.4

I have the following Models with corresponding tables:
User (users), UserProfile (user_profiles), Review (reviews)
Schema
table: users
user_id (primary key)
first_name
last_name
table: user_profiles
user_id (foreign key)
country
phone
table: reviews
reviewer_id (the user who posted the review)
user_id (foreign key)
body
I query the database with the following:
$user = User::with('profile', 'review')->find(Auth::User()->user_id);
Part of User Model
public function profile(){
return $this->hasOne(UserProfile::class, 'user_id');
}
public function review(){
return $this->hasOne(Review::class, 'user_id');
}
Part of UserProfile Model
public function users() {
return $this->belongsTo(User::class, 'user_id');
}
Part of Review Model
public function users() {
return $this->belongsTo(User::class, 'user_id');
}
How can I access the details of the reviewer using the reviewer_id from the users table
As a sunup of what was discussed in this question, I think the major concern of OP was regarding a table that have 2 foreign keys with the same table. Both user_id and reviewer_id are foreign keys linked to the users table.
One important thing to understand about Laravel relationships is that the relationship name is not hard bound, it can be anything as long as it makes sense to you. The related object will be available in the ATTRIBUTE with the exact name of the METHOD.
class User extends Model {
public function review() {
return $this->hasOne(Review::class);
}
}
A user's review will be available at User::find(1)->review;.
class Review extends Model {
public function owner() {
return $this->belongsTo(User::class, 'user_id');
}
public function reviewer() {
return $this->belongsTo(User::class, 'reviewer_id');
}
}
From a review, you will be able to access both users:
Review::find(1)->owner; // This is the relationship with user_id column
Review::find(1)->reviewer; // This is the relationship with reviewer_id column

Laravel Eloquent Relation Model

I have 3 table on my database :
table 1 = user (hasMany order)
table 2 = order (hasMany order_detail, belongsTo user)
table 3 = order_detail (belongsTo order)
On my order_detail model i add this function :
public function order() {
return $this->belongsTo('App\Order');
}
so i can call the order data without define it from controller, i just define order_detail on my controller
$order_detail->order->invoice_number
but how to call the user data from the order detail?
I try use this
$order_detail->order->user
but it didn't work for me..
Is there any idea to call the grand parent relation?
In order model add function for order_detail:
public function order_details() {
return $this->hasMany('order_detail');
}
and for user:
public function user() {
return $this->belongsTo('user');
}
In user model add:
public function orders() {
return $this->hasMany('order');
}
Then, you can call in the controller:
$details = Order::find(1)->order_details->where('order_detail_id', 5)->first();
$userName = $details->username;
// ^
// column name in order_detail table
More info in the docs.
I think this is the more complete way to define the relationships:
// User model
public function orders(){
// I'm telling that users has many order. The orders have an user_id field that match with the ID field of the user.
return $this->hasMany('App/Order', 'user_id' , 'id');
}
// Order model
public function order_details(){
// I'm telling that order has many order_details. The order_details have an order_id field that match with the ID field of the order.
return $this->hasMany('App/OrderDetail', 'order_id' , 'id');
}
public function user(){
// I'm telling that an order belongs to an user. The user has an ID field that match with the order_id field of the order.
return $this->belongTo('App/User', 'id', 'user_id');
}
// OrderDetail Model
public function order(){
// I'm telling that an order detail belongs to an order. The order has an ID field that match with the order_id field of the order detail.
return $this->belongTo('App/Order', 'id', 'order_id');
}
I have seen that you put just the model name as first parameter in your relation definition. I think you must put the relative path from the root to the Model. In my case, I have the models as childs of the App folder.

Resources