如何在laravel中的表N到N中获取元组?

时间:2014-04-14 14:39:59

标签: laravel controller laravel-4

我有以下数据模型

enter image description here

技术人员可以拥有许多服务,而服务可以拥有许多技术

Tecnico模型

class Tecnico extends Eloquent{
protected $table = 'Tecnico';
protected $fillable = array('Auth_Token');

public function servicios(){
    return $this->belongsToMany('Servicio', 'Servicio_Tecnico', 'idTecnico', 'idServicio');
}
}

Servicio模型

class Servicio extends Eloquent{
protected $table  = 'Servicio';

public function detalleServicio(){
    return $this->hasOne('Detalle_Servicio', 'idDetalle_Servicio');
}

public function tecnicos(){
    return $this->belongsToMany('Tecnico', 'Servicio_Tecnico', 'idServicio', 'idTecnico');
}
}

我正在尝试根据“auth_token”获取特定技术人员的所有服务

ServicioController

class ServicioController extends BaseController{

public function obtenerServicios($auth){

    if($auth != ''){
        $tecnico = DB::table('Tecnico')->where('Auth_Token',$auth)->first();
        if($tecnico != null){
            $servicio = $tecnico->servicios;
            $response = Response::json($tecnico);
            return $response;

        }else{
            $array = array('Error' => 'NotAuthorizedError', 'Code' => '403');
            $response = Response::json($array);
            return $response;
        }
    }else{
        $array = array('Error' => 'InvalidArgumentError', 'Code' => '403');
        $response = Response::json($array);
        return $response;
    }

}

}

路线

Route::get('servicio/{auth}', array('uses' => 'ServicioController@obtenerServicios'));

错误

enter image description here

我如何获得所有技术服务?

2 个答案:

答案 0 :(得分:1)

首先:最好使用Eloquent模型来查询而不是DB :: table。

例如:

$tecnico = Tecnico::with('servicio')->where('Auth_Token',$auth)->firstOrFail();

数据库查询构建器不知道Eloquent关系。 Eloquent只知道“查询”构建器。

第二:不要在URI中传递访问令牌。不在段中而不在查询字符串中。使用标题。

例如:

Route::get('servicio', 'ServicioController@obtenerServicios');

class ServicioController extends BaseController {

    public function obtenerServicios() {
        // strip the "Bearer " part.
        $token = substr(Request::header('Authorization'), 0, 7);
        // ...
    }
}

答案 1 :(得分:1)

使用Eloquent获取类似Model :: find()等的Eloquent结果(DB :: table ...将返回stdObject,这是你得到的错误),并纠正这些关系:

// class Tecnico
public function servicios(){
  // the keys are wrong:
  // return $this->belongsToMany('Servicio', 'Servicio_Tecnico', 'idTecnico', 'idServicio');

  // it should be like this:
  return $this->belongsToMany('Servicio', 'Servicio_Tecnico', 'Tecnico_idTecnico', 'Servicio_idServicio');
}

// class Servicio
public function tecnicos(){
    return $this->belongsToMany('Tecnico', 'Servicio_Tecnico', 'Servicio_idServicio', 'Tecnico_idTecnico');
}