Laravel 8 - 获取访问者用户详细信息
Posted
技术标签:
【中文标题】Laravel 8 - 获取访问者用户详细信息【英文标题】:Laravel 8 - Get Visitors User Details 【发布时间】: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
?
【参考方案1】:
所以我们这里只有两个模型,User
和 Profile
,还有一个 many-to-many relationship。 ProfileView
实际上只是两者之间的枢纽,因此不需要类定义。但假设时间戳是您想要访问的东西,您需要make allowances for that。
我会建议这样的事情:
class User extends Model
public function profile()
return $this->hasOne(Profile::class);
class Profile extends Illuminate\Database\Eloquent\Model
public function user()
return $this->belongsTo(User::class);
public function views()
return $this->hasMany(User::class, 'profile_views', 'profile_id', 'visitor_id')
->withPivot('created_at');
现在,要添加配置文件视图,您可以像这样编辑控制器方法(我假设 $user
是正在查看其配置文件的用户。)而不是创建枢轴的实例,您 attach 关系.我已经分离了以前的关系,假设你只想保留最近的关系。
public function profile(User $user)
$user->profile->views()->detach(Auth::id());
$user->profile->views()->attach(Auth::id());
return view('members.users.profile', compact('user'));
并检索信息:
<ul>
@foreach(Auth::user()->profile->views as $view)
<li> $view->name @ $view->pivot->created_at </li>
@endforeach
</ul>
这有点冗长,因为您的命名不符合 Laravel 约定,并且您选择将 profile_id
存储在数据透视表中而不是 user_id
但应该满足您的需要。
【讨论】:
以上是关于Laravel 8 - 获取访问者用户详细信息的主要内容,如果未能解决你的问题,请参考以下文章
使用 PHP Laravel 使用 Twitter API 获取授权用户详细信息