MorphMany to MorphTo relation - laravel

I have mangers table and funds table in my laravel project
Managers -> id, name, wallet
Funds -> id, amount, fundable_type, fundable_id, receivable_type, receivable_id, status
I have the following relations in Manager model
public function funds()
{
return $this->morphMany(Fund::class, 'fundable');
}
public function receiveds()
{
return $this->morphMany(Fund::class, 'receivable');
}
I have the following relations in Fund model
public function fundable()
{
return $this->morphTo();
}
public function receivable()
{
return $this->morphTo();
}
$manager->funds is populating fund models well.
I want to receive the managers who received fund a particular manager.
I tried $manager->funds->receivable but it is not working.

In relations specifications you can append the other model's relations:
public function funds()
{
return $this->morphMany(Fund::class, 'fundable')->with('receivable');
}

Okay, I was able to get the answer myself.
public function managers()
{
return $this->hasManyThrough(Manager::class, Fund::class, 'fundable_id', 'id', 'id', 'receivable_id')
->where('fundable_type', Manager::class)->where('receivable_type', Manager::class)->distinct();
}

Related

laravel model relationship seems backwards compared to docs

So I am setting up a one to one relationship between MyModel and the users table.
MyModel obviously has a user_id column to tie back to the users.
However - when i go to setup the relationship in MyModel I have to set it up in a way which seems backward!
This is in MyModel:
public function user()
{
return $this->hasOne('App\User', 'id', 'user_id');
}
Why Am i having to set the opposite foreign and local keys... ? Am i missing something?
Do it like this
class MyModel {
public function user()
{
return $this->belongsTo('App\User');
}
}
class User {
public function myModel()
{
return $this->hasOne('App\MyModel');
}
}
And that should work as intended (one to one) relationship

Laravel One to Many relation with 2 primary keys

I've 2 tables
Users table
id
name
...
Chats table
id
from_id // fk - id on users, the user sent the message
to_id // fk - id on users, intended user
message_body
Now, I'm trying to set up One to Many relation where user has many chat messages but a chat message has two user. from and to user
How can I define this relationship?. I have to user eager loading.
I tried to use Compoships but it didn't work.
My code
User Model
public function chats() {
return $this->hasMany(Chat::class, ['from_id', 'to_id'], 'id');
}
Chat Model
public function user() {
return $this->belongsTo(User::class, ['from_id', 'to_id'], 'id');
}
public function chats() {
return $this->hasMany(Chat::class, 'from_id', 'id') + $this->hasMany(Chat::class,'to_id','id');
}
public function userFrom() {
return $this->belongsTo(User::class, 'from_id', 'id');
}
public function userTo() {
return $this->belongsTo(User::class, 'to_id', 'id');
}
Why don't you do something like that?
On your User model, set up two relationships like this:
public function chatsFrom() {
return $this->hasMany('App\Chat', 'from_id');
}
public function chatsTo() {
return $this->hasMany('App\Chat', 'to_id');
}
Then, on your Chat model, also set up two relationships, one to from and another to to, both referencing a User model. Like this:
public function fromUser() {
return $this->belongsTo('App\User', 'from_id');
}
public function toUser() {
return $this->belongsTo('App\User', 'to_id');
}
This way, you can access the relationships using something like this:
$user->chatsFrom();
$user->chatsTo();
$chat->fromUser();
$chat->toUser();

How to retrieve details of second level tables in laravel relationships

I have 3 tables
bank(id, title),
employee(id, name, bank_id),
payroll(id, employee_id, salary).
Now I want to retrieve bank title of employee_id in payroll table.
I have set model relationships
class Bank extends Model
{
public function employees()
{
return $this->hasMany('App\Employee');
}
}
class Employee extends Model
{
public function bank()
{
return $this->belongsTo('App\Bank');
}
public function payrolls()
{
return $this->hasMany('App\Payroll');
}
}
class Payroll extends Model
{
public function employee()
{
return $this->belongsTo('App\Employee');
}
}
I have tried to retrieve using $payroll->employee->bank->title. But it did not help me
Sorry it was my mistake. some employee ids are not referencing bank. That was why I got error.
I resolved the issue by using isset method to verify reference value set or not.
Thanks.
try to change your code a little bit and try again:
public function bank()
{
return $this->hasOne('App\Bank');
}
Read Laravel Official Documentation
/** We can define the inverse of a hasOne relationship using the belongsTo method: **/

Laravel BelongsToMany with two pivot table

I have the following table structure:
products
id
product_formats
id
product_id
product_prices
id
product_format_id
market_id
markets
id
A product can have multiple formats, with each having their own price which belongs in a different market. How can I retrieve the list of Markets from the Product model?
I used to have a single pivot table, however now I have two pivot.
class Product extends Model
{
public function markets()
{
return $this->belongsToMany(Market::class);
}
}
Update
To get the result I want, I did the following:
public function markets()
{
return Market::whereIn('id', $this->prices()->distinct()->pluck('market_id')->toArray());
}
However, I'm wondering if there's a way to accomplish this via a relationship.
You need to build relationships in models.
ProductModel:
public function productFormats()
{
return $this->belongTo(ProductFormatsModel::class);
}
ProductFormatsModel:
public function productPrices()
{
return $this->belongTo(ProductPricesModel::class);
}
ProductPricesModel:
public function markets()
{
return $this->hasOne(MarketsModel::class);
}
in Controller:
foreach($product->productFormats as $productFormat)
{
foreach($productFormat->productPrices as $productPrice)
{
var_dump($productPrice->markets);
}
}
For unique markets
in ProductModel:
public function productPrices()
{
return $this->hasManyThrough(
'App\ProductPricesModel',
'App\ProductFormatsModel',
'product_id',
'product_format_id'
'id',
'id'
);
}
in Controller
foreach($product->productPrices as $productPrice)
{
var_dump($productPrice->markets)
}

Updated: Why relationship works when user is Admin, but won`t when Regular user?

I have 3 models: User, Role and Currency. I am confused about relationship between them.
Then User is Admin this works:
Auth::user()->currency->symbol)
When regular User I get error:
Trying to get property of non-object
if dd(Auth::user()) it show user, but cant access to relationship with model Currency. Why it is so?
User model relationship:
public function currency()
{
return $this->belongsTo(Currency::class, 'currency_id');
}
Currency model relationship:
public function created_by()
{
return $this->belongsTo(User::class, 'created_by_id');
}
If you need extra information, let me know.
User model
public function currency()
{
return $this->belongsTo(Currency::class);
}
Currency model
public function users()
{
return $this->hasMany(User::class, 'created_by_id');
}
Going with an assumption that your User model has an attribute currency_id
$this->belongsTo(TABLE, FORIEGN KEY, TABLE KEY);
refer this
User model
public function currency()
{
return $this->belongsTo(Currency::class, 'currency_id', 'id');
}
Currency model
public function users()
{
return $this->hasMany(User::class, 'created_by_id', 'id');
}

Resources