Laravel Scout-创建时不添加关系

时间:2019-06-14 06:14:04

标签: php laravel elasticsearch algolia laravel-scout

PHP:7.3

Laravel:5.8

Laravel侦察兵:7.1

Algolia Scout扩展:1.6

class Page extends Model
{   
  use Searchable;

  public function toSearchableArray()
  {
    $array = [
      'title' => optional($this->content)->title,
      'extra' => $this->extra,
    ];

    return $array;
  }

  public function content()
  {
    return $this->morphOne(Content::class, 'contentable');
  }

  protected $fillable = ['extra'];

  protected $with = ['content'];
}

class Content extends Model
{
    public function contentable()
    {
      return $this->morphTo();
    }

    protected $fillable = ['title'];

    protected $touches = ['contentable'];
}

class PageController extends Controller
{
  public function store(Request $request)
  {
    $page = Page::create($request->all());

    $page->content()->create($request->all());

    return $page;
  }

  public function update(Request $request, $id)
  {
    $page = $this->findOrFail($id);

    $page->update($request->all());

    $page->content->update($request->all());

    $page = $page->fresh();

    return $page;
  }
}

Scout导入现有实例的工作正常,所有实例都处于同步状态。

更新后,同步工作正常,$ touches可以完成工作。

$array = [
  'title' => 'Title',
  'extra' => 'Extra field',
];

在存储中,内容关系为空,创建后不会更新。

它似乎没有收听内容 保存事件。 (该关系已添加到 $ touch 数组中)。

$array = [
  'title' => null,
  'extra' => 'Extra field',
];

2 个答案:

答案 0 :(得分:1)

public function update(Request $request, $id)
  {
    $page = Page::with('Content')->findOrFail($id);

    $page->update($request->all());

    $page->content->update($request->all());

    $page = $page->fresh();

    return $page;
  }

它将起作用

答案 1 :(得分:0)

// use Content; // after namespace
class PageController extends Controller
{    
  public function store(Request $request)
  {
    $page = Page::with('content')->create($request->all());

    return $page;
  }
try this step