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

You might try using the morphToMany instead of belongsToMany.

I had to make a piviot table to hold my relationship. The process got a bit confusing.

http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Relations/MorphToMany.html http://laravel.com/docs/4.2/eloquent#many-to-many-polymorphic-relations

Last updated 2 years ago.
0

Thanks TerrePorter, I am not sure if that is what I needed.

I ended up with a resolution though, and I think it's bit of a hack and would welcome any suggestions on something cleaner.

I have extended my original Pupil model and created

<?php

class PupilWithSchoolIdentifier extends Pupil {

    protected $primaryKey = 'txtSchoolID';

}

I then use this model in my Set model

<?php

class Set extends \RHS\Eloquent\Model {

    protected $table = 'TblTeachingManagerSets';

    protected $primaryKey = 'TblTeachingManagerSetsID';

    protected $accessibleColumns = [
        'TblTeachingManagerSetsID',
        'intSubject',
        'intYear',
        'txtName',
        'txtTeacher',
    ];

    public function pupils()
    {
        return $this->belongsToMany('PupilWithSchoolIdentifier', 'TblTeachingManagerSetLists', 'intSetID', 'txtSchoolID');
    }


}

I have found the code that I want to adjust in the BelongsToMany class in Laravel.

protected function setJoin($query = null)
	{
		$query = $query ?: $this->query;

		// We need to join to the intermediate table on the related model's primary
		// key column with the intermediate table's foreign key for the related
		// model instance. Then we can set the "where" for the parent models.
		$baseTable = $this->related->getTable();

		$key = $baseTable.'.'.$this->related->getKeyName();

		$query->join($this->table, $key, '=', $this->getOtherKey());

		return $this;
	}

However this seems to always want to use the getKeyName method on the model, which returns the primary key. Perhaps it would be good to allow passing a parameter through so that the pivot foreign key can be specified/overridden?

As I say, what I have done works, but it feels a little dirty, I am sure there is a better way.

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.