我有三个表,一个Users表,一个Jobs表和一个Bids表。用户可以发布多个作业,用户可以对不属于他们的作业发布出价。
我的目标:我尝试查询Jobs表以查找所有用户作业,并查询Bids表以获取用户正在出价的所有作业。然后,我想根据他们的时间戳和返回职位ID对工作和出价进行排序
表格设置如下:
| USERS | JOBS | BIDS
| id | id | id
| username | user_id | user_id
| password | title | job_id
| | | bid_amount
表格之间的关系如下:
工作:
public function bids()
{
return $this->hasMany('App\RocketCandy\Repos\Bids\Bid');
}
public function user()
{
return $this->belongsTo('App\RocketCandy\Repos\Users\User');
}
用户:
public function jobs()
{
return $this->hasMany('App\RocketCandy\Repos\Jobs\Job');
}
public function bids()
{
return $this->hasMany('App\RocketCandy\Repos\Bids\Bid');
}
出价:
public function jobs()
{
return $this->belongsTo('App\RocketCandy\Repos\Jobs\Job');
}
public function users()
{
return $this->belongsTo('App\RocketCandy\Repos\Users\User');
}
我开发的以下代码会返回作业和出价,但根据updated_at时间戳对ID进行排序并不够聪明。
public function getUsersJobs($userId)
{
// Get the jobs that the user posted
$postedJobs = Job::where('user_id', $userId)
->lists('id')
->toArray();
// Get the jobs that the user is bidding on
$biddedJobs = Job::with('bids')
->whereHas('bids', function ($q) use ($userId) {
$q->where('user_id', $userId);
})->lists('id')
->toArray();
$jobIds = array_merge($postedJobs, $biddedJobs);
// Return the jobs that a user has posted and is bidding on
return Job::whereIn('id', $jobIds)
->OrderBy('updated_at', 'DESC')
->get();
}
答案 0 :(得分:2)
我认为你可以通过从用户而不是工作中查看它来简化它:
$jobs = User::where('user_id', $userId)->jobs;
$bids = User::where('user_id', $userId)->bids;
$all = $jobs->toBase()->merge($bids)->sortByDesc('updated_at');
foreach ($all as $thing) {
dump($thing->id);
dump($thing->updated_at);
}