在雄辩的ORM中具有数据库查询

时间:2018-11-21 19:26:19

标签: php laravel eloquent

让我告诉你我雄辩的ORM课程:

<?php

namespace App\Http\Models\Transport_Type;

use Illuminate\Database\Eloquent\Model;
use App\Http\Models\Transport_Type\TransportType;

class TransportType extends Model{

    public $timestamps = false;

    public function foo($language_id){
        $transport_types = TransportType::join('translations', 'transport_types.name', '=', 'translations.id')
                            ->join('translation_entries', 'translations.id', '=', 'translation_entries.translation_id')
                            ->where('translation_entries.language_id', '=', $language_id)
                            ->orderBy('parent_id')
                            ->get(['transport_types.id', 'transport_types.parent_id', 'translation_entries.value']);

        return $transport_types;
    }
}

如您所见,我具有foo函数,可以从许多不同的控制器调用该函数。所以这是我的问题:这是一种好习惯吗?还是应该将该查询逻辑移至控制器?

1 个答案:

答案 0 :(得分:1)

我更喜欢将雄辩的模型和控制器尽可能地保留为空,因为我更喜欢拥有用于处理所有数据访问权限的存储库。有关如何在Laravel中执行此操作的示例,请参见https://medium.com/employbl/use-the-repository-design-pattern-in-a-laravel-application-13f0b46a3dce

编辑:我不确定您的做法是否是好的做法。只是想分享我的意见,也许会有所帮助:)!