我跟着this tutorial让Laravel的Eloquent在现有的Codeigniter项目中运行,一切正常,直到我尝试使用Eloquent的关系。这是我的违规代码:
class Announcement_model extends Eloquent {
protected $table = 'announcements';
public function game() {
$this->load->model('game_model');
return $this->belongsTo('Game_model', 'game_id');
}
}
class Game_model extends Eloquent {
protected $table = 'games';
}
控制器:
class Api_announcement extends REST_Controller {
...
public function index_get() {
$response = Announcement_model::with('game')->get();
$this->response(array('error'=> false, 'response' => $response), 200);
}
}
我遇到了这个错误:
<b>Fatal error</b>: Uncaught exception 'LogicException' with message 'Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation' in myproject\vendor\illuminate\database\Eloquent\Model.php:2695
Stack trace:
#0 myproject\vendor\illuminate\database\Eloquent\Model.php(2665): Illuminate\Database\Eloquent\Model->getRelationshipFromMethod('load')
#1 myproject\vendor\illuminate\database\Eloquent\Model.php(2607): Illuminate\Database\Eloquent\Model->getRelationValue('load')
#2 myproject\vendor\illuminate\database\Eloquent\Model.php(3325): Illuminate\Database\Eloquent\Model->getAttribute('load')
#3 myproject\application\models\announcement_model.php(11): Illuminate\Database\Eloquent\Model->__get('load')
#4 myproject\vendor\illuminate\database\Eloquent\Builder.php(477): Announcement_model->game()
#5 [internal function]: Illuminate\Database\Eloquent\Builder->Illuminate\Database\Eloquent\{closure}()
#6 in
<b>myproject\vendor\illuminate\database\Eloquent\Model.php</b> on line
<b>2695</b>
我做错了什么?我上下寻找解决方案,但没有任何效果。
答案 0 :(得分:0)
return $this->belongsTo('Game_model', 'game_id')->select(array('name'));
以数组形式返回,但没有关系。你需要这个:
return $this->belongsTo('Game_model', 'game_id');