Laravel 5.5 How to add dynamic conditions inside a relationship?

前提是你 提交于 2019-12-10 21:49:19

问题


I have a relation to get the friends created on specific date which is working with a static date parameter

public function friends()
{
    return $this->hasMany(Friend::class)->where('created_at','2018-01-31');
}

But i need to get it for a dynamic date where the $request variable is unavailable inside a relation. I tried like this which is not working

public function friends($request)
{
    return $this->hasMany(Friend::class)->where('created_at',$request->date);
}

How can i solve this issue?


回答1:


You can use Laravel helper function request()

The request function returns the current request instance or obtains an input item

public function friends()
{
    $date = request('date') ? : '2018-01-31'; // You can choose a default date, here '2018-01-31'

    return $this->hasMany(Friend::class)->where('created_at', $date);
}



回答2:


Model will remain same as you posted:

public function friends($date)
{
    return $this->hasMany(Friend::class)->where('created_at', $date);
}

In your controller(example):

$fooFriends = $foo->friends('2018-01-30')->get();

//Directly from $request or you can use different values/vars each time
$fooFriends = $foo->friends($request->date)->get();



回答3:


You can do something like this in controller

public function data(){

    Mdalname::friend($value)
}

And in modal

public function friends($value )
{

    return $this->hasMany(Friend::class)->where('created_at', $value);
}


来源:https://stackoverflow.com/questions/48543763/laravel-5-5-how-to-add-dynamic-conditions-inside-a-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!