簡體   English   中英

Laravel和關系

[英]Laravel and relationships

我已經創建了一些這樣的表格,

新聞(id,news_titles_id,create_time)

新聞標題(ID,名稱)

現在為我的模特:

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雄辯的指南中的某些內容嗎?

您有如下表:

表格:新聞標題:(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;
}

我認為這應該是

return $this->hasOne('NewsTitle', 'news_title_id');

因為“新聞”對象“具有一個”新聞標題。

與關系相反,在NewsTitle模型上

public function news()
{
  return $this->belongsTo('News', 'news_title_id');
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM