【问题标题】:Laravel 4 - Models & One to ManyLaravel 4 - 模型和一对多
【发布时间】:2014-01-07 07:21:26
【问题描述】:

我正在尝试了解 laravel 模型和一对多...

我有以下表格

ww_bookings
-----------------------------
booking_id
customer_id
quote_id

ww_quotes
-----------------------------
quote_id
etc
etc
etc

我正在使用哨兵进行身份验证,基本上是在成功登录时,我想找到登录用户的 id,然后查询 ww_bookings 数据 WHERE customer_id = 'logged in user id'。

一旦 customer_id 的所有预订都很好,它就需要去查询每个发现的预订的 ww_quotes 并带回数据。

//Controller
BookingData::find(1)->quotes()->where('quote_id', '=', '1')->get();

//BookingData Model
class BookingData extends Eloquent {

protected $table = 'ww_bookings';
protected $primaryKey = 'customer_id';

public function quotes() {

  return $this->hasMany('QuoteData');

}


}

//QuoteData Model
class QuoteData extends Eloquent {

protected $table = 'ww_quotes';

}

我收到以下错误: 未找到列:1054 'where 子句'中的未知列 'ww_quotes.booking_data_id'(SQL:select * from ww_quotes where ww_quotes.booking_data_id = 1 和 quote_id = 1)

谁能帮帮我,这让我发疯了......

希望它有意义..

【问题讨论】:

    标签: php mysql laravel-4


    【解决方案1】:

    我看到了两个问题:

    错误的关系
    问题是 ww_quotes schema/table 应该包含引用 ww_booking schema/table 的键 - 正好相反。
    解决方法:

    ww_bookings
    -----------------------------
    customer_id
    quote_id
    
    ww_quotes
    -----------------------------
    quote_id
    booking_id
    

    密钥不匹配
    Eloquent 为关系生成和使用的键名将与现有的键名不匹配。如果你指定它们,Eloquent 会使用它们。

    return $this->hasMany('QuoteData', 'booking_id');
    

    【讨论】:

    • 感谢安德烈,但这会起作用吗,因为 1 位客户可以针对那里的 customer_id 进行多次预订??
    猜你喜欢
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 2018-04-29
    • 2016-05-25
    • 2016-07-12
    相关资源
    最近更新 更多