开发人员:))
我在laravel中建立了一种关系(多对多的多态)
之间:
暗示:用户可以喜欢他喜欢的任何人(衣服或鞋子......等)
用户模型:
class User extends Authenticatable
{
public function clothes()
{
return $this->morphToMany('Etrade\clothes\Clothes' ,'favoritable' )
->withTimestamps('created_at','updated_at');
}
}
服装模特:
class Clothes extends Model
{
// relationship with user
public function user()
{
return $this->morphToMany('Etrade\Users\User' ,'favoritable')
->withTimestamps('created_at','updated_at');
}
}
有利可图的模式:
class Favriable extends Model
{
protected $table = 'favoritables';
public function favoritable()
{
return $this->morphTo();
}
}
使用关系
获取数据- 获取给定衣服的所有用户:
$clo= Etrade\clothes\Clothes::find(35);
$clo->user; // fetch the relation
=> Illuminate\Database\Eloquent\Collection {#760
all: [
Etrade\Users\User {#761
id: 4,
name: "Reta Paucek",
email: "ahegmann@example.org",
gender: 0,
mobile: "",
city_id: 0,
active: 0,
friend_status: 1,
created_at: "2016-12-26 18:53:51",
updated_at: "2016-12-26 18:53:51",
pivot: Illuminate\Database\Eloquent\Relations\MorphPivot {#213
favoritable_id: 35,
user_id: 4,
created_at: "2016-12-30 03:34:58",
updated_at: "2016-12-30 03:34:58",
},
},
],
}
- 获取给定用户的所有衣服:
$user = Etrade\Users\User::find(4);
$user->clothes; // fetch the relationship
获取错误:
Column not found: 1054 Unknown column 'favoritables.clothes_id' in 'field list' (SQL: select
`clothes`.*, `favoritables`.`favoritable_id` as `pivot_favoritable_id`, `favoritables`.`clothes_id` as `pivot_clothes_id`, `favoritables`.`created_at` as `pivo
t_created_at`, `favoritables`.`updated_at` as `pivot_updated_at` from `clothes` inner join `favoritables` on `clothes`.`id` = `favoritables`.`clothes_id` where
`favoritables`.`favoritable_id` = 4 and `favoritables`.`favoritable_type` = Etrade\Users\User)'
我的问题:如何解决这个错误,,,关系在一个方向上工作不是为了两个?
答案 0 :(得分:0)
我认为您正确复制了代码,如果是,那么我可以在那里看到拼写错误,抱歉,但我还没有使用'评论'。
//Favriable, or Favoritable
class Favriable extends Model
{
protected $table = 'favoritables';
public function favoritable()
{
return $this->morphTo();
}
}
请注意,Laravel擅长使用蛇盒'要定义词汇或其他内容,请查看:
https://laravel.com/docs/5.3/eloquent#defining-models
我可以说在拼写方面你一定要小心Laravel的口才。她是严格而直接的。
另外,如果您的桌子被称为"收藏夹",则该模型应为"收藏"。 如果数据库中的表被称为" stars",那么模型应该是" Star",只是举几个例子。
希望这能启发一些事情。