Laravel在课堂上保存数据

柯蒂斯

我想做这样的事情。

namespace App\Repositories;

use Illuminate\Database\Eloquent\Relations\HasMany;

class SomeRepository {
    /**
     * HasMany
     */
    private $relation;

    public function __construct(HasMany $hasMany) {
        $this->relation = $hasMany;
    }

    public function setStatus($obj_id, $status) {
        $status_on = $this->getStatusOn();

        switch($status) {
            case 0:
                $status_on->status = 0;
                $status_on->save();
                break;
            case 1:
                $status_to_on = $this->relation->where('id', '=', $obj_id)->first();
                if ($status_on) {
                    $status_on->status = 0;
                    $status_on->save();
                }
                $status_to_on->status = 1;
                $status_to_on->save();
                break;
        }
    }

    public function getStatusOn() {
        return $this->relation->where('status', '=', 1)->orderBy('order', 'ASC')->first();
    }
}

在使用Afterget()获取所有关系时,无法通过获取任何数据$this->relation->where('status', '=', 1);

我在想,我应该使用newQuery吗?

我的问题是如何从MySQL获取数据并将其保留并在SomeRepository需要时获取数据(因为我需要能够随时过滤任何数据hasMany)。

我的设计中有些逻辑错误吗?或如何在Laravel中设计我想要的课程?非常感谢,对不起,我的英语不好。

维克多·阿努文邦(Victor Anuebunwa)

HasMany对象无法用于实现所需的对象,因为无法以所需的方式重复使用该对象。使用get()first()在对象中执行基础查询不会像预期的那样将其重置为构造函数中传递的先前状态。

function getBooks($model){
    $result = $model->get();
}

$model = new Book;
$books = getBooks($model);  //Gets books
$model = $model->where('published', true);
$books = getBooks($model);  //Gets only published books. Notice the where('published', true); condition called above on the model is still active?

重用时不再获得结果,relation因为对其执行的旧查询和条件仍处于活动状态。为了保持在构造函数中传递的对象的状态,您可能每次需要使用它时都要对其进行复制。

namespace App\Repositories;

use Illuminate\Database\Eloquent\Relations\HasMany;

class SomeRepository {
/**
 * HasMany
 */
private $relation;

public function __construct(HasMany $hasMany) {
    $this->relation = $hasMany;
}

private function copyRelation(){
  $clone = clone $this->relation;
  return $clone;
}

public function setStatus($obj_id, $status) {
    $status_on = $this->getStatusOn();

    switch($status) {
        case 0:
            $status_on->status = 0;
            $status_on->save();
            break;
        case 1:
            $status_to_on = $this->copyRelation()->where('id', '=', $obj_id)->first();
            if ($status_on) {
                $status_on->status = 0;
                $status_on->save();
            }
            $status_to_on->status = 1;
            $status_to_on->save();
            break;
    }
}

public function getStatusOn() {
    return $this->copyRelation()->where('status', '=', 1)->orderBy('order', 'ASC')->first();
}

注意我如何使用SomeRepository::copyRelation();

注意:代码未经测试,希望您能理解。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章