我是 Laravel 的新手,我有一个关于 Eloquent 的问题:
这是我的数据库表结构:
users
- id
- user_id
- username
- name
- password
- email_verified_at
- remember_tok
- created_at
- updated_at
challenges
- id
- challenge_id
- category_id
- hashtag
- title
- description
- duration
- link
- created_at
- updated_at
- user_id
user_challenges
- user_id
- challenge_id
- duration
- created_at
- updated_at
我想要实现的是显示用户的挑战,例如,如果用户在用户仪表板中加入挑战,我想显示他加入的挑战,以及用户创建的挑战(如果他创建了任何);
模型\用户.php
class User extends Authenticatable
{
use Notifiable;
public function challenges() {
return $this->hasMany(Challenge::class, 'user_id');
}
public function userChallenges() {
return $this->hasMany(UserChallenge::class, 'user_id');
}
}
模型\挑战.php
class Challenge extends Model
{
public function user () {
return $this->belongsTo(User::class, 'user_id');
}
}
模型\UserChallenge.php
class UserChallenge extends Model
{
public function user () {
return $this->belongsTo(User::class, 'user_id');
}
}
这是我的家庭控制器中的内容: App\Http\Controllers\HomeController.php
class HomeController extends Controller
{
public function index()
{
$user_id = auth()->id();
$user = User::find($user_id);
return view('home')
->with('challenges', $user->challenges)
->with('userChallenges', $user->userChallenges);
}
}
这是我目前在“我的仪表板”中获得的“加入挑战”的内容 - 但如何在返回视图时加入表格,以便我也可以获得挑战主题标签标题?就像我在“我的挑战”部分下获得的一样? 仪表板
更新:我应该将什么添加到我的数据库中,以便我可以计算已加入挑战的用户数量?
当年话下