我已经创建了几个表,
News (id, news_titles_id, create_time)
新闻标题(id, name)
现在为我的模型:
class News extends Eloquent {
protected $table = 'News';
public function title() {
return $this->belongsTo('newsTitles', 'news_titles_id');
}
}
class NewsTitles extends Eloquent {
protected $table = 'NewsTitles';
}
现在如果我尝试使用
$news = News::all();
echo $news->title->name;
我得到标题未定义属性错误。
我在这里做错了什么?我错过了什么吗?
您的表如下所示:
表:NewsTitles: (id, name)
表:News: (id, news_titles_id, create_time)
模型:
class NewsTitles extends Eloquent {
protected $table = 'NewsTitles';
public function news()
{
return $this->hasOne('News', 'news_title_id');
}
}
class News extends Eloquent {
protected $table = 'News';
public function title()
{
return $this->belongsTo('NewsTitles', 'news_title_id');
}
}
使用:
$news = News::with('title')->all(); // returns a collection (more than one)
echo $news->first()->title->name; // Get first News
echo $news->get(0)->title->name; // Get first News
echo $news->get(1)->title->name; // Get second News
或者你可以循环:
foreach($news as $item) {
echo $item->title->name;
}
我觉得应该是
return $this->hasOne('NewsTitle', 'news_title_id');
因为News对象"有一个"新闻标题。
在NewsTitle
模型中,关系的反比为
public function news()
{
return $this->belongsTo('News', 'news_title_id');
}