laravel BelongsTo relationship with different databases not working

后端 未结 9 942
無奈伤痛
無奈伤痛 2020-12-06 00:25

I\'ve seen in several places to \"stay away\" from this, but alas - this is how my DB is built:

class Album extends Eloquent {

   // default connection

            


        
9条回答
  •  日久生厌
    2020-12-06 00:42

    This is my own solution and it works in general for me but its mega-complicated.

    I'm using the builder "from" method to set the table and database correctly inside the subquery. I just need to pass the correct information inside.

    Assume the subquery can be as complicated as "genres.sample" or even deeper (which means albums has a relation to genres, and genres has a relation to samples) this is how

    $subQuery = 'genres.samples';
    $goDeep = (with (new Album));
    
    $tableBreakdown =  preg_split('/\./', $subQuery); //  = ['genres', 'samples']
    
    // I recurse to find the innermost table $album->genres()->getRelated()->sample()->getRelated()
    foreach ($tableBreakdown as $table)
        $goDeep = $goDeep->$table()->getRelated();
    
    // now I have the innermost, get table name and database name
    
    $alternativeConnection =  Config::get("database.connections." . $goDeep->getConnectionName() . ".database"); // should be equal to the correct database name
    
    $tableName = $goDeep->getTable(); // I have to use the table name in the "from" method below
    
    Album::whereHas($subQuery, function ($q) use ($alternativeConnection, $tableName) {
    $q->from("$alternativeConnection.$tableName"); 
    $q->where(....... yadda yadda);
        });
    

    tl:dr;

    Album::whereHas('genres', function ($q) { 
        $q->from('resources.genres')->where(....); 
    });
    

提交回复
热议问题