哪个是好的模型或控制器

时间:2021-01-13 13:34:58

标签: php laravel frameworks

我想在 Laravel 中构建一个复杂的项目(会有很多数据)。但我想在模型中编写我的代码(SQL 查询)。我不想在控制器中编写这些查询,我在模型中使用“Illuminate\Support\Facades\DB”,而不是在控制器中。所以我希望我的查询将在控制器中的模型和其他代码中。这个方法在 Laravel 中好用吗?我问这些是因为我在查询生成器在控制器中使用的其他来源中看到了这一点。使用模型但只使用表名或其他函数,因此其他来源在控制器中编写查询。我可以使用查询生成器在模型中编写我的查询吗?如下图。

<块引用>

控制器。

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\model_test1;

class model_test extends Controller
{
    function index(){
        $test = new model_test1;
        return $test->fetch();
    }
}
<块引用>

型号

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class model_test1 extends Model
{
    protected $table="users";
    public function fetch(){

        return  DB::table("users")->get()->where('id',2);

    }
}

1 个答案:

答案 0 :(得分:0)

您应该为每个模型创建存储库。一个存储库应该反映一个模型。

控制器应该调用存储库函数来访问数据。以下是存储库的示例。

<?php

namespace App\Repositories;

use App\Advertisement;
use App\JobAdvertisement;

class UserAdvertisementRepository
{
    /**
     * @param $employeeType
     * @param $userId
     * @return mixed
     */
    public function getAdvertisementBasedOnEmployeeType($employeeType, $userId)
    {
        return JobAdvertisement::where('employee_type', $employeeType)
            ->where('user_id', $userId)
            ->paginate(2);
    }

?>

您也可以为业务逻辑创建一个服务类。

相关问题