В Ларке есть связи Eloquent ORM может проще переписать? Или это не поможет Буду благодарен за статьи, книги и тд. Сам вряд ли осилю(
One To One
One To Many
One Of Many
Many To Many
Как можно сформировать такой вывод без hard coda? Или связи не правильные либо это невозможно
одним запросом
Array
(
[0] => Array
(
[id] => 1
[firstname] => James
[lastname] => Spiegel
[avatar] => author-page.jpg
[created_at] => 2021-08-18 13:42:17
[title] => My Perfect Vacations in South America and Europe
[description] => Lorem ipsum dolor sit amet
[count_likes] => 6
[count_comments] => 0
[count_shares] => 0
[images_photo] => Array
(
[0] => post-photo1.jpg
[1] => post-photo1.jpg
)
)
);
Вот этот кусок непонятно как сделать 1 запросом а не 2
[images_photo] => Array
(
[0] => post-photo1.jpg
[1] => post-photo1.jpg
)
Пришлось нахардкодить
$host = '127.0.0.1';
$port = '3307';
$db = 'app';
$user = 'root';
$pass = '';
$charset = 'utf8';
$auth = 1;
$dsn = "mysql:host=$host;port=$port;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
$query = 'SELECT users.id, users.firstname, users.lastname, users.avatar, posts.created_at, posts.id, posts.title, posts.description, ' .
'(SELECT COUNT(likes.id) FROM likes WHERE likes.post_id = posts.id) as count_likes,' .
'(SELECT COUNT(comments.id) FROM comments WHERE comments.post_id = posts.id) as count_comments,' .
'(SELECT COUNT(shares.id) FROM shares WHERE shares.post_id = posts.id) as count_shares,' .
'(SELECT COUNT(images.id) FROM images WHERE images.post_id = posts.id) as count_image' .
' FROM posts
INNER JOIN users ON users.id = posts.user_id AND users.id = ' . $auth;
$query1 = 'SELECT * FROM images';
$query2 = 'SELECT users.id, users.firstname, users.avatar, likes.post_id FROM likes INNER JOIN users ON likes.user_id = users.id ORDER BY likes.id ASC';
$posts = $pdo->query($query)->fetchAll(PDO::FETCH_ASSOC);
$images = $pdo->query($query1)->fetchAll(PDO::FETCH_ASSOC);
$likes = $pdo->query($query2)->fetchAll(PDO::FETCH_ASSOC);
function add($posts, $images, $likes)
{
foreach($posts as $key => $post)
{
foreach($images as $image)
{
if ($post['id'] === $image['post_id'])
{
$posts[$key]['images'][] = $image['img'];
}
}
foreach($likes as $like)
{
if ($post['id'] === $like['post_id'])
{
$posts[$key]['likes'][] = $like['avatar'];
$posts[$key]['users'][] = $like['firstname'];
}
}
}
return $posts;
}
$posts = add($posts, $images, $likes);
echo '<pre>';
print_r($posts);
echo '</pre>';