Laravel hasOneThrough - Laravel relationships - laravel

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

Related

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

How to properly implement this polymorphic relationship in Laravel?

I am trying to build an inventory for users in Laravel 5.8, however the items have their own properties, therefore I needed to set up a polymorphic relationship. When attaching items to users, it tries to add the model User to the table on itemable_type and the user's ID to itemable_id aswell as add the User's ID to user_id, something I could workaround by passing the models I need, but when I try to retrieve them it tries to find item with itemable_type = 'App\Models\User', which makes me think something's completely wrong here. Can I have some orientation on how to solve it?
class User extends Model
{
public function inventory()
{
return $this->morhpToMany(InventoryItem::class, 'itemable', 'user_inventories', null, 'itemable_id')
->withPivot('amount', 'notes');
}
}
class InventoryItem extends Model
{
public $timestamps = false;
protected $table = 'character_inventories';
protected $fillable = [
'character_id', 'itemable_type', 'amount', 'parent_id', 'notes'
];
public function cloth()
{
return $this->mophedByMany(Cloth::class, 'itemable');
}
public function food()
{
return $this->morphedByMany(Food::class, 'itemable');
}
// Other similar relations
}
// The Inventory migration:
Schema::create('user_inventories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->unsignedInteger('itemable_id');
$table->string('itemable_type');
$table->unsignedInteger('amount')->default(0);
$table->text('notes', 65535)->nullable();
$table->foreign('character_id')->references('id')->on('characters');
});
The expected result is the User model to have different items in his inventory, but the relation is trying to query by joinning to itself and filtering by user type instead of actual items.
The error:
Syntax error or access violation: 1066 Not unique table/alias: 'user_inventories' (SQL:
select `user_inventories`.*,
`user_inventories`.`itemable_id` as `pivot_itemable_id`,
`user_inventories`.`itemable_type` as `pivot_itemable_type`,
`user_inventories`.`amount` as `pivot_amount`,
`user_inventories`.`parent_id` as `pivot_parent_id`,
`user_inventories`.`notes` as `pivot_notes`
from `user_inventories`
inner join `user_inventories` on `user_inventories`.`id` = `user_inventories`.`itemable_id`
where `user_inventories`.`itemable_id` in (4)
and `user_inventories`.`itemable_type` = App\Models\User)
I highly suspect that you have to references the user table in the inventory relation. In general it is a million times easier just following the Laravel convention for naming.
public function inventory()
{
return $this->morhpToMany(InventoryItem::class, 'itemable', 'users', null, 'itemable_id')
->withPivot('amount', 'notes');
}

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

Many to Many Relationship Join Query between Two Table in Laravel 5.1

First User table have four columns: id ,first_name, last_name,password
my Address Table have four colmnns id , company_name,email , phone
Common Address_user Table:
My User Model Look Like This http://pastebin.com/ntuvJ8Lj and my Address Model Look Like This
use Illuminate\Database\Eloquent\Model;
class Address extends Model
{
protected $fillable = [
'created_by',
'company_name',
'phone',
'email', 'address'
];
public function users()
{
return $this->belongsToMany('App\Models\User');
}
public function getAddressListAttribute()
{
return $this->users->lists('id');
}
}
now I need the all of address which login user is involved or connected
1:
in User.php
Add your relation with 'address' model:
public function addresses() {
return $this->belongsToMany( Address::class, 'address_id', 'user_id' )->withTimestamps();
}
You wrote right relation in your Address.php with users therefore, I'm not going to retype it here.
and please note that you don't need to write address_id and user_id because simply eloquent will predict it if you are following the convention, which you do!
But I can tell that you are not following the convention of naming your tables, if you want Eloquent to predict and relation between your model and your table in DB then you have to make the name of your model the singular of your table name, or vice versa, table: users model: User.
The Gist:
$user = auth()->user(); // get logged in user
$addresses = $user->addresses()->get(); // get this user addresses. or use $user->addresses only
// now you may loop through it and have each of your addresses.
foreach($addresses as $address){
var_dump($address->company_name); // or perhabs ->email
}

Resources