左连接查询与eloquent

时间:2013-08-13 22:22:18

标签: join laravel laravel-4

我有两门课程:学位和大学,

class Degree extends Eloquent {
      public function title(){
         return $this->degree_title;
      }
      public function college(){
         return $this->belongsTo('College','college_code');
      }
}
class College extends Eloquent {
      public function title(){
         return $this->college_title;
      }
}

我将它设置为belongsTo,因为它在hasOne()上中断,错误是:

Call to a member function getResults() on a non-object

如果这是正确的方向,我不确定。

我一直在尝试的是使用slug搜索程度(它可以实现更好的分析),然后将结果传递给我创建的刀片。

注意:有一个Degrees表和一个Colleges表,我可以运行没有连接的查询:

学位控制器:

class DegreeController extends BaseController {
    public function single($slug)
       {
            $degree = Degree::where('slug', '=', $slug)->get();
            return View::make('degrees.single', array('degree' => $degree));
       }
}

单一视图:

@extends('master')
{{ -- Single Degree Blade-- }}
@section('content')

@foreach($major as $m)
    <div>
        <h1>{{ $m->title() }}</p>
        <p>{{ $m->college->title() }}</p>
        <p>Holland: {{ $m->holland() }}</p>
    </div>
@endforeach

@stop

我注意到使用$m->college->title()会导致错误: SQLSTATE [42S22]:未找到列:1054'where子句'中的未知列'collegess.id'(SQL:select * from colleges其中collegesid =?limit 1) (绑定:数组(0 =&gt;'UAGSC',))

这表明它忽略了我的自定义键,它不是id而不是整数,它是一个特定的5个字母varchar。

任何人都可以就如何处理此问题向我提出任何建议吗?

2 个答案:

答案 0 :(得分:0)

加入时,请使用主键。主要是身份证。

使主键成为INT和AUTO INCREMENT。

你会成功。

答案 1 :(得分:0)

我通过将College表的主键(ID)更改为college_code引用的相同值来解决它。 ID不是自动增量或整数,我正在使用已经唯一的标识符,从长远来看,这对我来说更容易。

相关问题