标签:extends UNC name this des function orderby data ted
模型里面
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
//
protected $table = "posts";
public $primaryKey = ‘id‘;
public function user()
{
return $this->belongsTo("App\Models\User","user_id",‘id‘);
}
public function comments()
{
return $this->hasMany(‘App\Models\Comment‘,‘post_id‘,‘id‘)->orderBy("created_at",‘desc‘);
}
}
控制器查询列表
$posts = Post::withCount("comments")->orderBy("created_at",‘desc‘)->paginate(6);
视图里面使用
{{ $post->comments_count }}
laravel使用withCount获取列表下关联模型的数量
标签:extends UNC name this des function orderby data ted
原文地址:https://www.cnblogs.com/php-linux/p/11689469.html