-1

PHP: 7.3

拉拉维尔: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;
  }
}

现有实例的侦察导入工作正常,所有实例都是同步的。

在更新同步工作正常, $touches 完成这项工作。

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

在存储中,内容关系为空,并且在创建时未更新。

看起来它不听内容 保存事件。(关系被添加到$touch数组中)。

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

2 回答 2

0
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;
  }

它会起作用的

于 2019-06-14T06:51:49.180 回答
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
于 2019-06-14T09:33:11.447 回答