topclaudy / compoships

Multi-columns relationships for Laravel's Eloquent ORM
MIT License
1.12k stars 130 forks source link

Let raw expresions be foreign keys #122

Closed erikn69 closed 3 years ago

erikn69 commented 3 years ago

Closes #121 Let raw expresions be foreign keys

Example:

use DB;
class A extends \Illuminate\Database\Eloquent\Model;
{
    use \Awobaz\Compoships\Compoships;

    public function b()
    {
        return $this->hasMany('B',
                ['foreignKey1', DB::raw('C.foreignKey2')], //can be more raws
                ['localKey1', 'localKey2']
            )
            ->join('C','C.other_key','=','B.other_key');
    }
}

Actual results:

(`B`.`foreignKey1`= 1 and B.C.foreignKey2 = 2)

Expected results:

(`B`.`foreignKey1`= 1 and C.foreignKey2 = 2)

maybe we can have more options with DB::raw() example

$this->hasMany('B',
    ['foreignKey1', DB::raw("SUBSTRING(B.code, 1, 2)")],
    ['localKey1', 'localPrefix']
);

results on

(`B`.`foreignKey1`= 1 and SUBSTRING(B.code, 1, 2) = 'US')

@topclaudy

mtawil commented 3 years ago

Hello @topclaudy,

Can you review this PR, merge it and make a release, please? This is important, it does not make any sense to wrap the expression with another raw :)

Thank you.

topclaudy commented 3 years ago

Released in 2.1.2. Thanks.