6
我目前有一個與Laravel 4的關係問題,我有一個與兩個組件在桌子上查詢的數據透視表錯誤單數名稱。我創建了一個數據透視表lands_objs和填充它:Laravel 4多對多的關係不工作,數據透視表沒有找到
型號有:
<?php
class Obj extends Eloquent
{
protected $guarded = array();
public static $rules = array();
public $timestamps = false;
public function land()
{
return $this->belongsToMany('Land');
}
<?php
class Land extends Eloquent
{
protected $guarded = array();
public static $rules = array();
public $timestamps = false;
public function objs()
{
return $this->belongsToMany('Obj');
}
}
這裏是我如何填充後的標準數據透視表。當然土地,OBJ文件和lands_objs表存在:
<?php
use Illuminate\Database\Migrations\Migration;
class CreateLandsObjsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('lands_objs', function($table) {
$table->integer('land_id');
$table->integer('obj_id');
});
}
}
通過這樣的結構,我應該能夠做到感謝雄辯:
$land = Land::find(1); //checked loads land fine
$objs = $land->objs; //--> HERE I TAKE THE ERROR
但我採取錯誤:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'taylor.land_obj' doesn't exist
(SQL: select `objs`.*, `land_obj`.`land_id` as `pivot_land_id`, `land_obj`.`obj_id`
as `pivot_obj_id` from `objs` inner join `land_obj` on `objs`.`id` = `land_obj`.`obj_id`
where `land_obj`.`land_id` = ?) (Bindings: array (0 => 1,))
儘管在land_obj上喋喋不休,Laravel不應該創建表lands_objs嗎?我錯過了什麼嗎?
非常感謝。
你能告訴我什麼是使用2種** **的belongsTo方法和** ** hasManyThrough方法之間的區別?我不明白,但使用hasManyTrough不適合我... – kitensei 2014-01-09 08:00:36
鑑於作者有很多帖子和一篇文章有很多評論的情況。你通常會有2個屬於方法的地方(作者可以發佈和發表評論),但是,如果你想選擇給定作者所有帖子的所有評論,那麼你會使用hasManyThrough,因爲評論不是直接與作者有關,但他們通過另一個模型(職位)與作者有關。如果沒有hasManyThrough,你必須選擇所有作者的帖子,然後循環他們得到所有的評論,然後做一些處理,讓他們進入你以前的格式/順序等。 – Brent 2014-03-07 05:48:21