有两种型号:分类和邮政。
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类 - 第2栏
第3类 - Post5
第4类 - 邮政15
一个类别 - 最后一个类别。
答案 0 :(得分:2)
您有Post
个// 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();
然后当你想要使用它时......
final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request.Builder ongoing = chain.request().newBuilder();
ongoing.addHeader("Cache-Control", "no-cache");
ongoing.addHeader("User-Agent", System.getProperty("http.agent"));
return chain.proceed(ongoing.build());
}
})
.connectTimeout(100, TimeUnit.SECONDS)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(globalUrl())
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();