我一直试图弄清楚如何实现匹配系统,但是却陷入困境。 我已经设法在控制器中建立了一个查询,该查询的功能与我想要的完全相同,但是我想将其转换为Eloquent模型,因为图像已损坏并且还可以访问模型中的某些功能。 / p>
这是我希望转换的控制器中的查询生成器(如果有可能)-我正在检查用户是否彼此“喜欢”(类似于Tinder):
class MatchedEmployersController extends Controller
{
public function index()
{
$matches = DB::table('applicant_likes')
->join('employers', 'employers.id', '=', 'applicant_likes.liked_employer_id')
->whereExists(function ($query) {
$query->select(DB::raw(1))
->from('employer_likes')
->whereRaw('employer_likes.employer_id = applicant_likes.liked_employer_id');
})
->get();
return view('applicant.employers.matched', compact('matches'));
}
}
这是“申请人”模型,下面我将逻辑提取为可用的特征
App\Models\Applicant
class Applicant extends Authenticatable
{
use Notifiable, LikeableEmployer, MatchableEmployer;
//
public function getAvatarAttribute($value)
{
return asset($value ?: '/images/default-avatar.jpeg');
}
}
App\Trais\LikeableEmployer
trait LikeableEmployer
{
public function likeEmployer(Employer $employer)
{
return $this->likedEmployers()->save($employer);
}
public function unlikeEmployer(Employer $employer)
{
return $this->likedEmployers()->detach($employer);
}
public function toggleLikeEmployer(Employer $employer)
{
if ($this->likingEmployer($employer)) {
return $this->unlikeEmployer($employer);
}
return $this->likeEmployer($employer);
}
public function likingEmployer(Employer $employer)
{
return $this->likedEmployers()->where('liked_employer_id', $employer->id)->exists();
}
public function likedEmployers()
{
return $this->belongsToMany(Employer::class, 'applicant_likes', 'applicant_id', 'liked_employer_id');
}
}
最后,这是匹配逻辑的放置位置
namespace App\Traits;
use App\Traits\LikeableApplicant;
use App\Traits\LikeableEmployer;
trait MatchableEmployer
{
use LikeableApplicant, LikeableEmployer;
public function matchedEmployers()
{
//
}
}
答案 0 :(得分:0)
您需要创建一个用于存储匹配项的表。让我们来看下面的例子。
relationships
table: id | from | to
,如果我们有一对,那就是一场比赛。示例:
id | from | to
1 | 1 | 2
2 | 2 | 1
现在创建Relationship
模型
class Relationship extends Model
{
public static function getMatch($user_id)
{
return self::leftJoin('relationship reverse', 'relationship.to', '=', 'reverse.from')->where('relationship.from', 'reverse.to')->where('relationship.from', $user_id)->get();
}
}
现在您可以简单地致电User::getMatch('any_user_id');
答案 1 :(得分:0)
首先,为您在此查询中使用的每个表创建模型,然后添加以下关系。
public function employer(){
return $this->belongsTo('App\Employer','liked_employer_id','id');
}
public function likes(){
return $this->hasMany('App\EmployerLike','employer_id','id');
}
public function index()
{
$matches = ApplicantLike::with('employer','employer.likes')
->has('employer')
->has('employer.likes')
->get();
// dd($matches); // try with this first
return view('applicant.employers.matched', compact('matches'));
}