2016-09-27 79 views
0

有兩種模式:分類和發佈。Laravel.get一個相關記錄

class Category extends Model 
{ 

    public function posts() 
    { 
     return $this->hasMany('App\Post','category_id'); 
    } 
} 

class Post extends Model 
{ 
    public function category() 
    { 
     return $this->belongsTo('App\Category'); 
    } 
} 
//Get data 
     $data = Category::with(['posts' => function($query){ 
      $query->orderBy('id','desc')->first(); 
      }])->get(); 

在這種情況下,所有類別都會顯示,並且只顯示一個帖子。我需要從每個類別中獲得一個記錄。

實施例:
第1類 - POST1
第2類 - POST2
類別3 - Post5
類別4 - Post15
一類 - 一個最後這一類訊息。

回答

2

你有一個Category與許多Post s,但你只是想獲得最新的職位,所以你可以添加另一種關係。

// Category.php 
class Category extends Model 
{ 
    // This gets ALL posts 
    public function posts() 
    { 
     return $this->hasMany('App\Post','category_id'); 
    } 

    // This gets the most recent post 
    // I am ordering by created_at instead of ID, but you can use ID 
    // if it makes sense for your application) 
    public function mostRecentPost() 
    { 
     return $this->hasOne('App\Post','category_id') // hasOne is the key here 
        ->orderBy('created_at', 'DESC'); 
    } 
} 

然後,當你想使用它......

$data = Category::with('mostRecentPost')->get(); 
+0

糟糕!我誤解了這個問題:-) –