我对laravel是个新手,我确信我做错了什么。
我有两张桌子。Cities和users_metadata
我的cities表看起来像这样
id | City |
1 | New York |
1 | Los Angeles |用户元数据
user_id | firt name | last name | cities_id |
1 | Jonh | Doe | 2 |所以我的问题是,当我创建一个关系时,我得到的是纽约,因为城市id与用户id相匹配。
城市模型
class City extends Eloquent
{
public static $table = "cities";
public function profile()
{
return static::has_many('Profile');
}
} 配置文件模型
class Profile extends Eloquent
{
public static $timestamps = false;
public static $table = "users_metadata";
public static $key = "user_id";
public function city()
{
return static::has_one('City');
}
} 错误
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'profile_id' in 'where clause'
SQL: SELECT * FROM `cities` WHERE `profile_id` = ? LIMIT 1
Bindings: array (
0 => 1,
)如果我没有将id传递给has,我会得到以下错误
好的我明白了。
所以我的问题是,我是否能够以某种方式在我的关系中传递外键cities_id以进行匹配?还是我做错了?谁能给我举个基本的例子?
谢谢你们
发布于 2013-05-17 04:23:30
试试这个:
城市模型
class City extends Eloquent
{
public static $table = "cities";
public function profile()
} 配置文件模型
class Profile extends Eloquent
{
public static $timestamps = false;
public static $table = "users_metadata";
public static $key = "user_id";
public function city()
{
return static::belongs_to('City');
}
}我遇到了同样的问题,我认为我应该使用has_one,但我需要使用belongs_to。User1808639可能无法工作,因为在城市模型中仍然有一个'has_many‘。
发布于 2013-01-16 19:36:14
试试这个:
class Profile extends Eloquent
{
public function city()
{
return $this->belongs_to('City'); // city_id in the table
}
}发布于 2013-01-15 18:48:18
Laravel有一种自动检测外键的方法。因此,对于您的数据库架构...这个模型应该可以很好地工作,试试下面的方法
user_id | firt name | last name | city_id | //city not cities
1 | Jonh | Doe | 2 |-
class Profile extends Eloquent
{
public static $timestamps = false;
public static $table = "users_metadata";
public function city()
{
return $this->has_one('City');
}
}/
class City extends Eloquent
{
public static $timestamps = false;
public function profiles()
{
return $this->has_many('Profile');
}
}https://stackoverflow.com/questions/14335723
复制相似问题