if
关系处理中的命令你好,工匠,美好的一天,
拜托,我需要有关
if
命令不适用于关系的帮助。我想获得 hashCard
的正确关系,但只有默认关系有效。 if
语句不会检查 status
模型的 UserHashCard
字段,该模型使用枚举 ('available', 'initiated', 'joined', 'completed'
)。
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UserHashCard extends Model {
protected $guarded = [];
public function hashCard() {
return $this->belongsTo(HashCard::class);
}
// Uncomment if needed
// public function exchanges()
// {
// return $this->hasMany(HashCardExchange::class, 'hash_card_id');
// }
public function initiatedExchanges()
{
return $this->hasMany(HashCardExchange::class, 'hash_card_id', 'hash_card_id');
}
public function joinedExchanges()
{
return $this->hasMany(HashCardExchange::class, 'hash_card_id', 'join_card_id');
}
public function exchanges()
{
if ($this->status == 'initiated') {
return $this->initiatedExchanges();
} elseif ($this->status == 'joined') {
return $this->joinedExchanges();
}
// Default relationship (e.g., for 'available' or other statuses)
return $this->initiatedExchanges();
}
}
Controller Code
php
Copy code
public function getHashCards() {
$user = User::find(Auth::user()->id);
$hashCards = $this->allCards($user->id);
return response()->json($hashCards);
}
private function allCards($userid)
{
$user = User::find($userid);
// Fetch UserHashCards with their exchanges and associated usernames
$hashCards = UserHashCard::query()
->where('user_id', $user->id)
->with([
'hashCard', // Existing relationship
'exchanges' => function ($query) {
$query->with(['user:id,username']); // Eager load only the `id` and `username` fields from `users`
}
])
->orderByRaw("
CASE
WHEN status = 'initiated' THEN 1
WHEN status = 'joined' THEN 2
ELSE 3
END
")
->get();
return $hashCards;
}
我前段时间也遇到过几乎同样的问题。我想获取具有活跃订单的用户,这就是它的工作原理:
public function getUsersWithActiveOrders() {
$users = User::with('orders')->get();
$users->transform(function ($user) {
$user->active_orders = $user->orders->filter(function ($order) {
return in_array($order->status, ['pending', 'shipped']);
});
return $user;
});
return response()->json($users);
}
就您而言,我认为您没有使用您定义的关系。应该是这样的:
public function conditionalExchanges() {
if ($this->status == 'initiated') {
return $this->initiatedExchanges;
} elseif ($this->status == 'joined') {
return $this->joinedExchanges;
}
return collect();
}
现在在您的控制器中,调用关系:
public function getHashCards() {
$user = User::find(Auth::user()->id);
$hashCards = $this->allCards($user->id);
$hashCards->each(function ($hashCard) {
$hashCard->conditional_exchanges = $hashCard->conditionalExchanges();
});
return response()->json($hashCards);
}
对于 allCards 功能:
$hashCards = UserHashCard::query()
->where('user_id', $user->id)
->with('hashCard')
->orderByRaw("
CASE
WHEN status = 'initiated' THEN 1
WHEN status = 'joined' THEN 2
ELSE 3
END
")
->get();
如果此后有问题,请告诉我。