Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent
Last updated 2 years ago.
0

I've tried to get the result I want with this code:

//In the contact model
public function getOrganisationAttribute() {
	return $this->client()->getResults()->organisation->toArray();
}

The $this->client()->getResults() bit instead of $this->client is needed because otherwise the whole Client model is appended to the Contact model, which I want to prevent. The toArray() is needed to prevent the Organisation object from being strangely parsed.

But this code breaks normal relations. If I try to get the client model attached to the contact while this organisation attribute is called, it doesn't attach it.

Last updated 2 years ago.
0

Hi Adam,

don't think it's still relevant for your project eight months ago, but for future occurrences and fellow Laravelers I'm posting my stuff here. I've had a similar problem and managed to work it out without problems. In my case I have a Store which belongs to an Address which can have multiple Coordinates attached. In order to obtain the Coordinates for the Store I used the following:

// In Store model
public function coordinates()
{
    return $this->address->hasMany('Coordinate');
}

I chose the hasMany method because Laravel expects a return value of type Illuminate\Database\Eloquent\Relations\Relation when using relationship methods.

For you I think it would translate to something similar to the following:

// In the contact model
public function organisation()
{
    return $this->client->belongsTo('Organisation');
}

The returned object in my case was a Collection of Coordinates so the model was left intact and I think that should work for other relationships, too.

I'm till pretty new to wholehearted PHP development and especially Laravel. Therefore I don't know much of the internal workings, yet and this solution's maybe not as good as I think, but it gets the job done.

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.