【问题标题】:laravel move query function from routes to repositorylaravel 将查询功能从路由移动到存储库
【发布时间】:2014-10-28 10:28:47
【问题描述】:

嗨,我对 laravel 的世界还很陌生,我正在建立一个存储库,因为我正在重复对数据库的如此多的调用,所以将它们全部保存在一个地方并参考这个是有意义的。无论如何,我有一个链式选择,它查看 client_id 并找到与该客户端匹配的项目。我让它在我的 routes.php 文件中工作:

 Route::get('task/clientsprojects', function(){
       $input = Input::get('option');
       $client = Client::find($input);
       $projects =  $projects = Project::where('client_id', $client->id) 
                        ->orderBy('project_name') 
                        ->get(array('id','project_name') 

                        );
   $response = array(); 
   foreach($projects as $project){ 
   $response[$project->id] = $project->project_name; 
  } 

  return Response::json($response);
});

我的 create.blade.php 文件中有一个:

   <!--These two select boxes are linked together --->
@if(count($client_options)>0)
        {{ Form::select('client', $client_options, Input::old('client'), array('data-placeholder' => 'Choose a Client...', 'id' => 'select_client', 'class' => 'chosen-select tempus_select', 'tabindex' => '2', )) }}
    @endif 

 {{ Form::select('project', array_merge(array('default' => 'Select client first')), 'default', array('class' => 'tempus_select', 'id' => 'project_select')) }}

<script>
$(document).ready(function($){ 
    $('#select_client').change(function(){ 
        $.get("/task/clientsprojects",{ 
            option: $(this).val() 
            }, function(data) { 
            console.log(data); 
            var model = $('#project_select'); 
            model.empty(); 
            $.each(data, function(key, value) { 
$('#project_select').append("<option value='"+key+"'>"+value+"</option>'");
            });
            $("#project_select").trigger("change");
        }); 
    });
});

</script>

我在我的存储库类中创建了这个函数:

 //fetch clients
public function getClients() 
    {

        return \Auth::user()->clients()->orderBy('client_name', 'asc')->lists('client_name','id');;
    }

 //fetch clients projects
public function getClientsProjects() {

    $input = Input::get('option');
    $client = Client::find($input);

    $projects = $projects = \Auth::user()->projects()->where('client_id', $client->id)->orderBy('project_name')->get(array('id','project_name'));

        $response = array(); 

        foreach($projects as $project){ 
        $response[$project->id] = $project->project_name; 
        } 

        return Response::json($response);
    }

我的控制器是这样引用 repo 的:

<?php
use Acme\Repositories\ProjectRepositoryInterface;
class TaskController extends \BaseController {

    public function __construct(ProjectRepositoryInterface $project) {

        $this->project = $project;

    }

public function create()
{
    //
     $tasks = Auth::user()->tasks;  

    $client_options = $this->project->getClients();


    return View::make('tasks.create', array( 'client_options' => $client_options, 'status' => $status, 'priority' => $priority));
}       

}

我现在如何将此选择路由到此函数以通过 ajax 检索数据?有谁知道我该如何进行?在上面的例子中,我在任务控制器中,我在 create 函数中获取我的客户端,在当前的实现中,我有 routes.php 捕获这个并执行查询我想将它更改为 repo,但我不确定如何实现这一点。

更新

我将我的 repo 更新为以下内容:

public function getClientsProjects() {

    $input = Input::get('option'); //line 42
    $client = Client::find($input);

$projects =  $projects = Project::where('client_id', $client->id) 
                           ->orderBy('project_name') 
                          ->get(array('id','project_name'));
        $response = array(); 

        foreach($projects as $project){ 
        $response[$project->id] = $project->project_name; 
        } 

        return $response;    
}

并将以下函数插入到我的控制器中:

public function clientsProjects()
{
    return Response::json($this->project->getClientsProjects());
} 

这是我的 routes.php 文件:

Route::get('task/clientsprojects', 'TaskController@clientsProjects');

但我在控制台中收到此错误:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)     
http://tempus.local/task/clientsprojects?option=1
XHR finished loading: GET "http://tempus.local/task/clientsprojects?option=1".
Failed to load resource: the server responded with a status of 500 (Internal Server Error) 

Laravel 日志:

[2014-09-03 20:20:45] production.ERROR: exception 
'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 
'Acme\Repositories\Input' not found' in 
/media/sf_Sites/tempus/app/Acme/Repositories/DbProjectRepository.php:42
 Stack trace:
#0 [internal function]: Illuminate\Exception\Handler->handleShutdown()
 #1 {main} [] []

【问题讨论】:

  • 好吧,一方面,在您的 repo 中调用 getClientsProjects 方法,然后尝试使用 getClients 从控制器调用它
  • getClients 是从我想获取他们的项目@MitchGlenn 的客户端加载客户端所需的不同调用

标签: php json laravel eloquent laravel-routing


【解决方案1】:

您必须首先从存储库中仅返回相关数据:

public function getClientsProjects($clientId) 
{
    $client = Client::find($clientId);

    ...

    return $response;
}

然后改变你的路由指向你的控制器:

Route::get('task/clientsprojects', 'TaskController@clientsProjects');

然后在您的控制器中执行以下操作:

use Input; /// before your class declaration

...

public function clientsProjects()
{
    $clientId = Input::get('option');

    return Response::json($this->project->getClientsProjects($clientId));
} 

【讨论】:

  • 啊,好的,我已按照您的建议将其移至相应位置,但现在控制台出现错误,我将发布更新@AntonioCarlosRibeiro
  • 我们需要完整的错误信息。查看您的服务器日志/var/log/&lt;webservername&gt; 它应该会告诉您出了什么问题。而且,也许 Laravel 也是如此:/var/www/appdir/app/storage/log/laravel.log
  • 您在存储库顶部缺少use Input
  • 经过编辑使其在设计方面看起来更好。我从存储库中删除了输入并将其传输到控制器,通过方法参数将客户端 ID 传递给控制器​​。
  • 你知道如何在我的选择下拉列表中实现占位符@if(count($client_options)&gt;0) {{ Form::select('client', $client_options, Input::old('client'), array('data-placeholder' =&gt; 'Choose a Client...', 'id' =&gt; 'select_client', 'class' =&gt; 'chosen-select tempus_select', 'tabindex' =&gt; '2', )) }} @endif这里的占位符没有区别
猜你喜欢
  • 2017-12-12
  • 1970-01-01
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-14
  • 2019-12-08
  • 2019-12-06
相关资源
最近更新 更多