Laravel Jensenggers Eloquent 模型排序主模型与关系模型

Laravel Jensenggers Eloquent Model sort main model with relation model

我正在尝试通过关系模型的列对主模型的整个数据集进行排序。我正在使用 Laravel ORM 5.2.43Jensenggers MongoDb 3.1

这是我的模型

UserEventActivity.php - Mongo 型号

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 型号

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class HandsetDetails extends Eloquent 
{

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

}

StoreDetails.php - MySql 型号

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 脚本

$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();

来自 UserEventActivity 的数据未根据手机关系中的 handset_make 字段存储。

请帮我达到预期的效果

据我所知MongoDB不支持这样的连接。

一种解决方法是使用预先加载。

因此您的 UserEventActivity 模型可能如下所示:

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;
    }


}

注意 getHandsetMakeAttribute() 访问器。 那么您也许可以通过以下方式拨打电话:

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

完全没有测试但值得一试。