user101289
user101289

Reputation: 10422

laravel relationship without morphing

I have an existing DB that I need to use (without modifying) for a project using laravel.

There's an Accounts table, a Vendor table, and a Contacts table. Contacts can belong to either an Account or a Vendor, in a belongTo/hasMany relationship.

The Contacts table has an Owner column that keys to the primary key of either the Accounts or Vendor table.

As I understand it the "right" way to do this in the laravel world is using morphing, where you'd add contactable_id and contactable_type columns in the Contacts table, and go from there.

However, since I can't modify the DB, I need a way to work using the existing relationship.

I can do something sort of hackish by adding a method to the Contact class like this:

public static function account_contacts()
{
    return DB::table('Contacts')
        ->join('Accounts', 'Contacts.Owner', '=', 'Accounts.ID');
}

However this returns an array of arrays instead of Contact objects.

Is there a way to get actual Contact objects back, or to create the relationship without using morphing?

EDIT: sorry for the lack of clarity in what I need. I just want to get all Account::Contacts or all Vendor::Contacts as an array of Contacts so I can iterate them using them as Contact models, instead of arrays.

Upvotes: 0

Views: 366

Answers (2)

alepeino
alepeino

Reputation: 9771

To answer your immediate question (that is, converting a plain array into an Eloquent model), you could do:

$ids = DB:table('Contacts')
           ->join('Accounts', 'Contacts.Owner', '=', 'Accounts.ID')
           ->forPage($pageNumber, $totalPerPage)
           ->pluck('id');

return Contact::findMany($ids);

Upvotes: 1

Iamzozo
Iamzozo

Reputation: 2358

Both belongsTo and hasMany second parameter is the foreign key, which you can change. Also you can add a where condition to it - if it's necessary, you can leave where condition, if there isn't such a field, and one Contact only belongs to one model.

If I understand your question correctly, you can setup your relations forexample for Accounts model:

public function contacts()
{
    return $this->hasMany('App\Contact', 'Owner')->where('type', 'accounts');
}

For Vendor model:

public function contacts()
{
    return $this->hasMany('App\Contact', 'Owner')->where('type', 'vendor');
}

Upvotes: 0

Related Questions