编程语言
首页 > 编程语言> > php – Laravel Jensenggers Eloquent模型排序主模型与关系模型

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

作者:互联网

我试图通过关系模型列对主模型的整个数据集进行排序.我正在使用Laravel ORM 5.2.43和Jensenggers 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的这些数据不是基于手机关系中的handheld_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();

根本没有测试,但值得一试.

标签:php,mysql,mongodb,laravel-eloquent,jenssegers-mongodb
来源: https://codeday.me/bug/20190706/1392822.html