[英]Laravel Scout/Algolia: Model relationships not pulling through to index
我有 3 個模型——Products、Users 和 UserProducts。 UserProduct 是特定產品的實例,具有用戶對該項目的特定價格、產品代碼等。 因此,一個產品可以有許多用戶產品,並且通過這些用戶產品,可以有許多用戶。 這些關系在產品 model 中定義:
public function userProducts() {
return $this->hasMany(UserProduct::class);
}
public function users() {
return $this->belongsToMany(User::class, 'user_products');
}
我知道這些關系正在發揮作用,因為在 Artisan Tinker 中,我將其中任何一個作為屬性調用時都會得到結果。
在我的 Algolia產品索引中,我希望結果包含有關用於過濾的相關用戶和用戶產品的信息。 因此,我按照 Scout Extended 和 Algolia 文檔中的建議加載這些關系:
public function toSearchableArray() {
$this->users;
$this->userProducts;
$array = $this->toArray();
// Apply Scout Extended default transformations:
$array = $this->transform($array);
return $array;
}
一切都在順利進行,但由於某種原因,'users' 和 'user_products' 都變成空的了。
具有“用戶”和“產品”關系的 UserProducts 在將這些關系拉入我的user_products索引之前成功加載了這些關系,這讓情況變得更加混亂:
由此,我只能得出結論,問題一定在於我如何設置填充數據庫的工廠文件。 對於 UserProducts,我使用了一個簡單的工廠:
<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\UserProduct;
use Faker\Generator as Faker;
$factory->define(UserProduct::class, function (Faker $faker) {
return [
'code' => 'EAN' . $faker->ean8,
'price' => $faker->randomFloat(2, 5, 1000),
'product_id' => App\Product::all()->random()->id,
'user_id' => App\User::where('type', 'supplier')->inRandomOrder()->first()->id
];
});
……而在 User 工廠中發生的事情要復雜一些:
$factory->define(User::class, function (Faker $faker) {
return [
'display_name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'phone' => $faker->phoneNumber,
'type' => array_rand(['supplier', 'buyer']),
'profile_completed' => true,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
});
$factory->afterCreating(User::class, function ($user, $faker) {
$user->assignRole($user->type);
if($user->type==='supplier') {
// create five products for them
$products = factory(App\Product::class, 5)->create();
$products->each(function($product) use ($user) {
$user_product = factory(App\UserProduct::class)->create([
'product_id' => $product->id,
'user_id' => $user->id
]);
})->each(function($product){
$product->setUserProductCount();
$product->update();
});
}
});
在 afterCreating 回調中所做的所有更改都已成功執行。 但是,無論對這段代碼進行多少改動,添加 $product->searchable() 等似乎都可以將必要的數據帶到我的產品索引中。 任何有用的建議將不勝感激。
可能是您忘記在產品 model 上使用 Laravel 的touch
功能。請參閱https://www.algolia.com/doc/framework-integration/laravel/indexing/configure-searchable-data/?language=php#更新關系時父子更改
讓我知道這是否能解決您的問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.