我想获取一些没有直接关系的表的数据。上下文如下:
//** account_table **// Normal user, who can buy any book
account_id
account_info
//** book_table **// Books
book_id
account_id
author_id
//** author_table **// Author, who can write a lot of books (they will have more functions, this is the why i choose to create other table)
author_id
book_id
author_desc
我使用的模型是:
class Account extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'account_table';
protected $primaryKey = 'account_id';
public function Book()
{
return $this->hasMany('Book', 'account_id');
}
public function Author()
{
return $this->hasManyThrough('Author', 'Book','account_id','book_id');
}
}
class Book extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'book_table';
protected $primaryKey = 'book_id';
public function Account()
{
return $this->belongsTo('Account','account_id');
}
public function Author()
{
return $this->hasOne('Author', 'author_id', 'author_id');
}
}
class Author extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'author_table';
protected $primaryKey = 'author_id';
public function Book()
{
return $this->belongsToMany('Book', 'author_id');
}
}
因此,为了获取此信息,我使用以下代码:
$user = Account::find(166); //user
dd($user->Author);
输出会抛出这样的错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'book.id' in 'on clause' (SQL: select `author_table`.*, `book_table`.`account_id` from `author_table` inner join `book_table` on `book_table`.`id` = `author_table`.`book_id` where `book_table`.`account_id` = 166)
它似乎正在寻找一个在我的数据库中不存在的字段 (id),但是我已经在模型中定义了所有主键。在这种情况下,我应该怎么做才能获得 author_desc
信息?
编辑(其他示例):
当我使用以下代码时,它检索到相同的错误:
$user = Account::find(166);
echo Book::find(3);
最佳答案
您已经使用 hasOne()
方法定义了 Book 与 Author 的一对一关系,并使用 belongsToMany( )
方法。相反,这些应该是反向关系。尝试用 belongsTo()
方法替换 belongsToMany()
方法。像这样:
class Account extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'account_table';
protected $primaryKey = 'account_id';
public function Book()
{
return $this->hasMany('Book', 'account_id');
}
public function Author()
{
return $this->hasManyThrough('Author', 'Book','account_id','book_id');
}
}
class Book extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'book_table';
protected $primaryKey = 'book_id';
public function Account()
{
return $this->belongsTo('Account','account_id');
}
public function Author()
{
return $this->hasOne('Author', 'author_id', 'author_id');
}
}
class Author extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'author_table';
protected $primaryKey = 'author_id';
public function Book()
{
return $this->belongsTo('Book', 'author_id');
}
}
关于php - hasManyThrough关系返回错误的SQL语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26829173/