php 当我想进入控制器时,有条件地调用laravel访问器吗?

um6iljoc  于 2023-03-21  发布在  PHP
关注(0)|答案(1)|浏览(100)

在我的laravel app控制器中,我想检索一个用户参与的聊天,我将用户ID附加到请求本身,然后在controlelr中创建一个名为chat_receiver的laravel模型访问器,如果我每次检索聊天模型时都附加这个访问器,我也会得到chat_receiver,这样我就不会同时检索两个聊天参与者(user_id,receiver_id),但是我并不总是想得到访问器。
所以问题是,有没有一种方法可以在需要的时候调用控制器中的accessor,而不是追加它,比如我如何使用Model::with([ 'relationship ])...
我的访问者在聊天模型:

public function getChatReceiverAttribute()
    {
        $request = resolve(Request::class);
        $user_id = $request->get('user_id', false);

        if($user_id)
        {
            if($user_id == $this->user->id)
            {
                //return $this->receiver;
                
                return 
                [
                    'id' => $this->receiver->id,
                    'name' => $this->receiver->name,
                    'lat' => $this->receiver->lat,
                    'lng' => $this->receiver->lng,
                    'images' => $this->receiver->images,
                    'sexuality' => $this->receiver->sexuality,
                    'birthYear' => $this->receiver->birthYear,
                    'birthMonth' => $this->receiver->birthMonth,
                    'birthDay' => $this->receiver->birthDay,
                    'gender' => $this->receiver->gender,
                    'fcm_token' => $this->user->fcm_token,
                    'languageCode' => $this->user->languageCode,
                    'mood' => $this->user->mood,
                    'description' => $this->user->description,
                ];
                
            }
            else
            {
                //return $this->user;
                
                return 
                [
                    'id' => $this->user->id,
                    'name' => $this->user->name,
                    'lat' => $this->user->lat,
                    'lng' => $this->user->lng,
                    'images' => $this->user->images,
                    'sexuality' => $this->user->sexuality,
                    'birthYear' => $this->user->birthYear,
                    'birthMonth' => $this->user->birthMonth,
                    'birthDay' => $this->user->birthDay,
                    'gender' => $this->user->gender,
                    'fcm_token' => $this->user->fcm_token,
                    'languageCode' => $this->user->languageCode,
                    'mood' => $this->user->mood,
                    'description' => $this->user->description,
                ];
                
            }
        }
        else
        {
            return [];
        }
    }

先谢了。

4ioopgfo

4ioopgfo1#

而不是将其添加到appends数组中。您可以在需要时通过编程添加它。如果您查看Model trait HasAttributes.php的代码。您可以看到您可以根据需要添加附加属性。为此,使用了高阶函数集合助手。

Model::where('something', 'something')
    ->get()
    ->each
    ->append(['chat_receiver']);

为单个模型添加它将是。

$model->append(['chat_receiver']);

相关问题