2016-11-23 5 views
2

私はLaravelを初めて使っています。私はbranchcluster_infoに参加したい魅力的なモデルに参加するLaravel 5.3

Schema::create('cluster_info', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->string('code')->unique(); 
      $table->string('pa_lastname'); 
      $table->string('pa_firstname'); 
      $table->string('pa_middlename'); 
      $table->string('pa_suffix'); 
      $table->integer('branch_id'); 
      $table->timestamps(); 

     }); 
Schema::create('cluster_grouping', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->integer('cluster_id'); 
      $table->integer('client_id'); 
      $table->timestamps(); 

     }); 
Schema::create('branch', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->string('code')->unique(); 
      $table->string('name'); 
      $table->string('region'); 
      $table->timestamps(); 

     }); 

: はここに私のスキーマです。だから私のCluster_Infoモデルに:

public function Branches(){ 
     return $this->hasOne('App\Branch'); 
    } 

と私は私のコントロールでそれを呼び出したとき、それはnull

$cluster = new App\Cluster_Info; 
dd($cluster->Branches()); 
+2

'branch'の' cluster_info'の外部キーは何ですか? – Tiger

+1

cluster_infoテーブルのブランチテーブルに外部キーを定義します。 –

+0

@BalrajAllamどのように私はclusteri_infoのブランチテーブルの外部キーを定義できますか? –

答えて

0

を持っているものは、外部キーとどのようにあなたがあなたのテーブルに外部キーを作成することが可能であることをhereをお読みください。 laravelの命名規則の説明を参照してくださいhere

テーブル名と外部キーを適切に追加した場合、関係が機能するはずです。そうでなければ、以下のメソッドを使用して、外部キーを2番目のパラメータとして渡すことができます。関係するためには、存在するので、それは、あなたがあなたのコントローラに書いたように、関係の方法かもしれません

return $this->hasOne('App\Branch', 'id', 'cluster_id'); 

必要があります:あなたのローカルおよび外部キーをチェックOne to One Relationship

return $this->hasOne('App\Branch', 'foreign_key'); 
0

ためDeatilsを読みます

$clusters = Cluster_Info::all(); 
foreach($clusters as $clusterInfo) { 
    dump($clusterInfo->Branches()); 
} 

eager loadingを使用して::

このように、既存の Cluster_Infoインスタンス上で要求されます
$clusters = Cluster_Info::with('Branches')->get(); 

また、Ellaquentがあなたのテーブル名を知っていることを確認してください。私はLaravelの規則をここで満たしているかどうかはわかりません。それだけで一つだけの結果を返す必要がありますため

class Cluster_Info { 
    protected $table = 'cluster_info'; 
} 

は読みやすくするために、私は、branch()代わりにBranches()のような方法を使用して助言します。またEloquent model conventionsを見て、あなたの人生をはるかに簡単にすることができます。

+0

iveは熱心なローディングを試みましたが、これが結果です カラムが見つかりません:1054 'where句'の中の 'branch.cluster__information_id'が不明です(SQL:select * from 'branch'ここで' branch'.cluster__information_id' in(1、 2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26、配列番号27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51、 52,53,54,64,67)) –

+0

更新された回答の最初の行を参照してください。 –

関連する問題