嗨,我想创建一个过滤器以仅显示具有事件或活动的清真寺。有任何想法仅通过活动或事件来展示清真寺吗?来自后端的这个稍后将使用react来获取
namespace App\Http\Controllers;
use App\Event;
use App\Mosque;
use App\Activity;
use Illuminate\Http\Request;
class NotificationController extends Controller
{
public function list()
{
$mosques = Mosque::get();
$array = array();
foreach ($mosques as $mosque) {
array_push($array, [
'mosque_name' => $mosque->name,
'mosque_image'=> $mosque->image
]);
}
return $array;
return response()->json(['result' => $mosques]);
}
public function show(Request $request)
{
$mosque = Mosque::find($request->mosque_id);
$mosque->activities;
$mosque->events;
return response()->json(['result' => $mosque]);
}
}
答案 0 :(得分:1)
要从数据库中过滤具有特定关系的行,可以在whereHas()
上使用QueryBuilder Instance
函数。
$mosques = Mosque::whereHas('events')
->orWhereHas('activities')
->get();
此函数将仅返回mosques which has activities or events
,其他mosques
将不会获取。
如果您只需要name
和image
,也可以过滤它们
$mosques = Mosque::whereHas('events')
->orWhereHas('activities')
->get(['name','image']);
答案 1 :(得分:-1)
您可以尝试
public function show(Request $request)
{
$mosque = Mosque::find($request->mosque_id);
$mosque->activities;
$mosque->events;
return response()->json(['result' => $mosque->events ]);
}