gpt4 book ai didi

php - 如何在php中创建一对多关系

转载 作者:行者123 更新时间:2023-11-28 23:45:13 25 4
gpt4 key购买 nike

我之前在 laravel 工作过。所以最近我搬到了核心 php,所以我正在尝试一对多关系。但它总是返回单独的记录。我有以下表格

作者

id | username | created_by | updated_by

书籍

id | author_id | book_name | book_image |

查询

select * from authors left join books  on author.id=books.author_id

我正在看我的结果,有点像这样

Array
(
[0] => Array
(
[id] => 1
[name] => Norm

[books] => Array
(
[0] =>Array
(
[id] => 4
[book_name] => great wall
[created_at] => 2015-09-11 04:45:07
[updated_at] => 2015-09-11 04:45:07
)

[1] =>Array
(
[id] => 6
[book_name] =>new book
[created_at] => 2015-09-11 04:45:07
[updated_at] => 2015-09-11 04:45:07
)
)
)
[1] => Array
(
[id] => 2
[name] => Norm

[books] => Array
(
[0] =>Array
(
[id] => 2
[book_name] => amazing star
[created_at] => 2015-09-11 04:45:07
[updated_at] => 2015-09-11 04:45:07
)

[1] =>Array
(
[id] => 3
[book_name] =>way of journy
[created_at] => 2015-09-11 04:45:07
[updated_at] => 2015-09-11 04:45:07
)
)

)


but in core php i am getting ouput


Array
(
[0] => Array
(
[id] => 1
[username] => david
[created_by] =>
[user_id] => 1
[books] => book1
)

[1] => Array
(
[id] => 2
[username] => david
[created_by] =>
[user_id] => 1
[books] => book2
)

[2] => Array
(
[id] => 3
[username] => david
[created_by] =>
[user_id] => 1
[books] => book3
)


[3] => Array
(
[id] => 5
[username] => miller
[created_by] =>
[user_id] => 2
[books] => new1
)

[4] => Array
(
[id] => 6
[username] => miller
[created_by] =>
[user_id] => 2
[books] => new2
)

)

所以我想在很多书上显示作者姓名。谁能帮帮我,我该怎么做

最佳答案

class Author extends Model
{
/**
* Get the books for the author.
*/
public function books()
{
return $this->hasMany('App\Book');
}
}

...

class Book extends Model
{
/**
* Get the atuhor that owns the book.
*/
public function post()
{
return $this->belongsTo('App\Author');
}
}

-- Laravel Documentation

关于php - 如何在php中创建一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33728294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com