Laravel hasManyThrough 2 tables - php

i have two tables as below:
users table:
|id|name|email|password|created_at|updated_at
messages table:
|id|sender_id|receiver_id|message|created_at|updated_at
User model:
public function threads()
{
return $this->hasManyThrough(Message::class, User::class,'id','sender_id');
}
i'm trying retrieve message threads
which isn't working. any help appreciated.

This is an example from laravel eloquent relationship
class Country extends Model
{
public function posts()
{
return $this->hasManyThrough(
'App\Post',
'App\User',
'country_id', // Foreign key on users table...
'user_id', // Foreign key on posts table...
'id', // Local key on countries table...
'id' // Local key on users table...
);
}
}
can you review your code

It seems that you want to retrieve all messages that belongs to a single thread (list of users) using hasMany relationship Through User model, to do that You have to define hasManyThrough inside Thread model not in User model, here is an example:
User:
|id|name|email|password|created_at|updated_at|thread_id
Note thread_id foreign key because thread is a list of users
Thread:
class Thread extends Model {
public function messages() {
return $this->hasManyThrough(Message::class, User::class,'thread_id','sender_id', 'id', 'id');
}
}
Example from laravel doc

Related

Speed up query through laravel relationships

There are 3 models:
First (first_id)
Connection (connection_id, first_id, product_id)
Second (second_id, product_id)
I would like to connect the three models together using laravel relationships
First->joined to Connection though first_id
Connection->joined to First through first_id, & joined to Second through product_id
Second -> joined to Connection through product_id
So: First joined to Second through Connection first_id, product_id
Is this possible to do using something like HasManyThrough?
Thanks for your time
On your First model:
public function second () {
return $this->hasManyThrough(
Second::class,
Connection::class,
'product_id', // Foreign key on connection table
'product_id', // Foreign key on second table
'first_id', // Local key on first table
'first_id' // Local key on connection table
);
}
Based on your description the column names should work.
In tinker you can validate if it's hooked up correctly by doing something like First::first()->second.
It depends on what type of relationship Your first model and second model shares as well as what type of relation second and third model shares.
if consider your first model First and second model Second shares a one-to-one relation, as well as Second model and Third models shares one-to-one relationships.
It will be $first->second->third; //no has many through relationship requires
If your First model and Second models shares as hasMany-belongs to relation than you need to use hasManyThrough relationship
example from doc
class Country extends Model
{
public function posts()
{
return $this->hasManyThrough(
'App\Post',
'App\User',
'country_id', // Foreign key on users table...
'user_id', // Foreign key on posts table...
'id', // Local key on countries table...
'id' // Local key on users table...
);
}
}
You can try using nested relationships.
Nested Eager Loading
To eager load nested relationships, you may use "dot" syntax. For example, let's eager load all of the book's authors and all of the author's personal contacts in one Eloquent statement:
$books = App\Book::with('author.contacts')->get();
Book Model:
public function author()
{
return $this->hasOne('App\Author');
}
Author Model:
public function contacts()
{
return $this->hasMany('App\Author');
}
Documentation:
https://laravel.com/docs/5.8/eloquent-relationships

Set Foreign Key to Null in One to Many Relationship in Laravel 5

My question is related to Laravel 5.6. I have Post and Category models. They have one-to-many relationship, with category_id as foreign key in posts table. The category_id is nullable field
//Post Model
class Post extends Model
{
public function category()
{
return $this->belongsTo('App\Category', 'category_id', 'id');
}
}
//Category Model
class Category extends Model
{
public function posts()
{
return $this->hasMany('App\Post', 'category_id', 'id');
}
}
My question is, If I delete a category. How do I set category_id to null for all the associated posts in posts table ?
I know laravel provide dissociate method, but I think it is for belongsTo relationship. Is there something similar to below?
$category::find($id);
$category->posts()->dissociate(); //set all foreign key(category_id) to null in posts table
$category->delete();
You don't want to take care of this yourself, let the foreign key handle it (as suggested by CD001):
Schema::create('posts', function (Blueprint $table) {
[...]
$table->foreign('category_id')->references('id')->on('categories')
->onDelete('set null');
});

BelongsTo relation Laravel 5.4 not working

I have two models (see below). With a one to many relationship, the HasMany relationship is working as expected, but the inverse belongsTo doesn't get any results when I try to do this.
$user = Auth::user();
dd($user->location->name);
I have the following database structure
Table locations
id
name
slug
Table users
id
name
email
password
location_id
remember_token
App/User model
public function location() {
return $this->belongsTo( 'App\Models\Location' );
}
and the App\Models\Location model
public function users()
{
return $this->hasMany('App\User');
}

Laravel Relationship in a pivot model

I have three tables, one of them is pivot table (and pivot model) and trying to create belongsTo relationship in pivot model (foreign key in pivot table) so that I can get the relevant name from some other table(has primary key). What I want to do is illustrating by images below:
Pivot Table is:
And other table is:
It is pivot Model:
class MproductIngredient extends Model {
public function qtyType() {
return $this->belongsTo('App\TIngredientType','priQuantityTypeNo');
}
}
How to get the relevant name from other table(has primary key).
My code is:
#foreach($prd->ingredients a $ingredient)
"{!! $ingredient->pivot->priQuantityTypeNo !!}"
#endforeach
Please describe more as far i understand you can make below to relationships
for belongstoMany
public function qtyTypes()
{
return $this->belongsToMany('App\TIngredientType', 'pivot_table_name',
'main_table_id', 'TIngredientType_id');
}
for hasOne
public function qtyType()
{
return $this->hasOne('App\TIngredientType');
}

Laravel foreign key relation

I've got a strange problem.
I've a users table and a company table. A User belongsTo a company and a company hasMany users.
Both primary keys of the table are id.
In the laravel documentation I read the following:
Additionally, Eloquent assumes that the foreign key should have a
value matching the id column of the parent.
I've got this in my CompanyModel:
protected $table = 'company';
public function users()
{
return $this->hasMany(UserModel::class);
}
When I try this:
$users = CompanyModel::find(1)->users;
dd($users);
It's not working. When I add a foreign key in my relation it works!?:
protected $table = 'company';
public function users()
{
return $this->hasMany(UserModel::class, 'id');
}
This is strange right? What on earth am I doing wrong.
--EDIT--
In my users table I've got a company_id column!
Firstly, I would suggest you rename your Model from CompanyModelto Company and from UserModel to User.
Then ensure you have company_id in your users table. And in your users migration file connect the users table with the companies table as such:
$table->integer('company_id')->unsigned();
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
Don't forget to refresh your database.
Then in your models, define the relationships as such:
// User model
// Laravel will automatically identify and use the `company_id` field in your reference
public function company(){
return $this->belongsTo(Company::class);
}
// Company model
public function users(){
return $this->hasMany(User::class);
}
You can then fetch your records in your controller as such:
$user = User::find(1);
$user_company = $user->company; // This might not be necessary in your controller, you can do it in your view
dd($users, $user_company);

Categories