Search code examples
phpmysqlmongodbjenssegers-mongodbeloquent

Laravel Jensenggers Eloquent Model sort main model with relation model


I'm trying to sort entire dataset of main model through column of relational model. I am using Laravel ORM 5.2.43 and Jensenggers MongoDb 3.1

Here are the models I have

UserEventActivity.php - Mongo Model

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class UserEventActivity extends Eloquent 
{

    protected $collection = 'user_event_activity';
    protected $connection = 'mongodb';

    public function handset() {

        return $this->hasOne('HandsetDetails', '_id', 'handset_id');
    }

    public function storeDetail() {

        return $this->hasOne('StoreDetails', 'st_id', 'store_id');
    }

}

HandsetDetails.php - Mongo Model

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class HandsetDetails extends Eloquent 
{

    var $collection = 'user_handset_details';
    var $connection = 'mongodb';

}

StoreDetails.php - MySql Model

use Jenssegers\Mongodb\Eloquent\HybridRelations;
use Illuminate\Database\Eloquent\Model as Eloquent;

class StoreDetails extends Eloquent 
{

    use HybridRelations;

    protected $connection = 'mysql';
    protected $table = 'icn_store';

}

Php script

$activity = UserEventActivity::join('handset ', 'handset._id', '=', 'handset_id')
    ->join('storeDetail', 'store_id', '=', 'storeDetail.st_id')
    ->orderBy('handset.handset_make', 'desc')
    ->select('storeDetail.*', 'handset.*')
    ->get()
    ->toArray();

This data from UserEventActivity is not stored based on handset_make field in handset relation.

Please help me to achieve the expected result


Solution

  • As far as I know MongoDB does not support joins like this.

    A way around it could be to use eager loading.

    So your UserEventActivity model might look like this:

    use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
    
    class UserEventActivity extends Eloquent 
    {
    
        protected $collection = 'user_event_activity';
        protected $connection = 'mongodb';
    
        public function handset() {
    
            return $this->hasOne('HandsetDetails', '_id', 'handset_id');
        }
    
        public function storeDetail() {
    
            return $this->hasOne('StoreDetails', 'st_id', 'store_id');
        }
    
        public function getHandsetMakeAttribute()
        {
            return $this->handset->handset_make;
        }
    
    
    }
    

    Note the getHandsetMakeAttribute() accessor. Then you may be able to make your call with this:

    $activity = UserEventActivity::with('storeDetail')
        ->with('handset')
        ->get()
        ->sortByDesc('handset_make')
        ->toArray();
    

    Not at all tested but worth a go.