In Laravel 5.5,I have three tables.
posts
id - integer
name - string
users
id - integer
nickname - string
images
id - integer
url - string
imageable_id - integer
imageable_type - string
Then we add the morphTo association to the images model.
public function imageable()
{
return $this->morphTo();
}
Problem:
Images::with(['imageable:id,name'])->get();
A problem found in the above use process is that when we design the table, the fields in posts and users are different, then there will be a requirement to judge in with whether the source of the table is posts or users to query different The table fields have the desired effect.
Similar to whereHasMorph:
Images::whereHasMorph(
'imageable',
[Users::class, Posts::class],
function (Builder $query, $type) {
if ($type === Users::class) {
$query->selectRaw("id,nickname");
} elseif ($type === Posts::class) {
$query->selectRaw("id,name");
}
}
);
At present, no effective way has been found to achieve this purpose. The only one that can be achieved is as follows.
$imageUsers = images::with([
'imageable' => function ($query) {
$query->selectRaw("id,nickname");
}
])->where('imageable_type', 'App\Users')->get();
$imagePosts = images::with([
'imageable' => function ($query) {
$query->selectRaw("id,name");
}
])->where('imageable_type', 'App\Posts')->get();
So, My question is how to determine whether the source of the table is posts or users in with to query different table fields to achieve the desired effect.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire