【发布时间】:2021-06-15 02:34:22
【问题描述】:
我想将 users 表获取或加入到我的 cmets 表中。但我不知道该怎么做 我使用 hasMany 将所有 cmets 表添加到 posts 。我想加入 users 表到
这是我的模特帖子
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Posts extends Model
{
use HasFactory;
public function comments(){
return $this->hasMany(Comments::class,'posts_id');
}
}
这是我的 PostsController 我使用 hasMany 与 posts 和 cmets 表
namespace App\Http\Controllers;
use App\Models\Posts;
class UserController extends Controller
{
public function index(){
return Posts::with('comments')->get();
return view('welcome',['authors'=>$authors]);
}
}
我的 PostsController 的输出使用 hasMany
[
{
"id": 1,
"post": "im in relationship now",
"comments": [
{
"posts_id": 1,
"comments_id": 1,
"users_id": 1,
"comments": "sweet"
},
{
"posts_id": 1,
"comments_id": 2,
"users_id": 2,
"comments": "grats"
},
{
"posts_id": 1,
"comments_id": 3,
"users_id": 3,
"comments": "wow"
},
{
"posts_id": 1,
"comments_id": 4,
"users_id": 4,
"comments": "grats dudes"
}
]
},
{
"id": 2,
"post": "im graduate now",
"comments": [
{
"posts_id": 2,
"comments_id": 5,
"users_id": 5,
"comments": "stay strong"
},
{
"posts_id": 2,
"comments_id": 6,
"users_id": 6,
"comments": "sweets"
},
{
"posts_id": 2,
"comments_id": 7,
"users_id": 7,
"comments": "ayiee"
}
]
}
]
在输出中,您看到 cmets 有一个 users_id,我想加入 users 表以获取该表的信息,例如名称和用户名
【问题讨论】:
标签: laravel eloquent has-many-through has-many