我创建了一些像这样的表,
新闻(id,news_titles_id,create_time)
NewsTitles(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;
我在标题上收到了未定义的属性错误。
我在这里做错了什么?我是否错过了Laravels雄辩的指南?
答案 0 :(得分:1)
您有以下表格:
表:NewsTitles:(id,name)
表:新闻:(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;
}
答案 1 :(得分:0)
我认为需要
return $this->hasOne('NewsTitle', 'news_title_id');
因为新闻对象“有一个”新闻标题。
NewsTitle
模型上关系的倒数是
public function news()
{
return $this->belongsTo('News', 'news_title_id');
}