【问题标题】:Laravel Jensenggers Eloquent Model sort main model with relation modelLaravel Jensenggers Eloquent Model 排序主模型和关系模型
【发布时间】:2017-05-07 21:11:30
【问题描述】:

我正在尝试通过关系模型列对主模型的整个数据集进行排序。我正在使用 Laravel ORM 5.2.43Jensengers 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 字段进行存储。

请帮助我达到预期的效果

【问题讨论】:

    标签: php mysql mongodb jenssegers-mongodb laravel-eloquent


    【解决方案1】:

    据我所知,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();
    

    根本没有经过测试,但值得一试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-08
      • 2016-02-26
      • 2019-08-11
      • 2021-10-01
      • 2018-10-20
      • 2021-07-04
      • 2017-01-12
      • 1970-01-01
      相关资源
      最近更新 更多