【发布时间】:2022-01-23 21:55:12
【问题描述】:
希望能有所帮助。我已经为此苦苦挣扎了一段时间,不确定我是否缺少明显的东西。
我有一个用户配置文件设置,当有人查看它时,它会将那个人的用户 ID 存储在一个表中。我想创建一个“谁访问过我”,它将显示访问过他们个人资料的那个人的用户详细信息。
到目前为止,一切正常,但我无法让访问者显示详细信息。
这是我目前所拥有的
用户模型
public function profile()
{
return $this->hasOne(Profile::class);
}
public function profileViews(){
return $this->hasMany(ProfileView::class, 'profile_id');
}
ProfileView 模型
protected $fillable = [
'profile_id',
'visitor_id',
];
public function users()
{
return $this->belongsTo(User::class);
}
配置文件控制器
public function profile(User $user)
{
$profile_id = $user->id;
ProfileView::updateOrCreate(['visitor_id' => Auth::user()->id, 'profile_id' => $profile_id, 'updated_at' => now()]);
return view('members.users.profile', compact('user' ));
}
以防万一你需要它,我的个人资料访客表迁移
个人资料查看表
public function up()
{
Schema::create('profile_views', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('visitor_id');
$table->unsignedBigInteger('profile_id');
$table->timestamps();
$table->foreign('visitor_id')
->references('id')
->on('users')
->onDelete('cascade');
});
}
这是我在谁拜访过我中所拥有的(这是我正在努力的地方,所以正在玩耍
@foreach(Auth::user()->profileViews as $view)
{<li>{{ $view->user->name }} </li>}
@endforeach
【问题讨论】:
-
试试 public function profileViews(){ return $this->hasMany(ProfileView::class, 'visitor_id','profile_id'); }
-
updateOrCreate接受 2 个参数(第一个:要搜索的属性,第二个:要更新的值),您将继续使用您所拥有的内容创建一个新记录,因为您正在使用时间戳进行搜索不匹配 -
我错过了 updateOrCreate。 @lagbox 关系是否正确?
-
关系方法名称应该是
user(单数)而不是users(复数)顺便说一句,您必须定义正在使用的键,因为它不是user_id;在这种情况下visitor_id....profileViews关系是否有效?它如何知道用户的profile_id? -
profile_id是用户的id?
标签: laravel