2017-09-01 105 views
0

我有兩個MSSQL表,所以我創建了兩個模型[Adress]和[Webshop]。外鍵是兩個表中的Adresse。如何檢索Laravel 5.4中的一對一關係數據

1.型號[ADRESS]

class Adress extends Model 
{ 
    protected $table = "Adress"; 
    protected $primaryKey = 'Adresse'; 
    public $timestamps = false; 

    public function webshop() 
    { 
     return $this->hasOne('App\Webshop', 'Adresse'); 
    } 
} 

2.型號[網上商店]

class Webshop extends Model 
{ 
    protected $table = "Webshop"; 
    protected $primaryKey = 'Adresse'; 
    public $timestamps = false; 

    public function adress() 
    { 
     return $this->belongsTo('App\Adress','Adresse'); 
    } 
} 

我想作的表與從第一和第二表像webshopID一些數據,手機在[網上商店]表中,並在[地址]表中添加地址。我認爲這是兩張表格之間的一對一關係。

php artisan tinker

App\Adress::all();   -> this is working 
App\Adress::find(2910)->webshop -> this is also working 
App\Adress::with('webshop')->get() -> this is NOT working 

我想在同一時間檢索從這個兩個表的數據。這是可能與一個關係,或者我希望使用連接?

編輯: 也許我foreignKeys是錯誤的

ADRESS表: enter image description here

網上商店表: enter image description here

+0

您的模型都有'protected $ primaryKey ='Adresse';'?看起來有點不可思議,或者是「Adresse」你的默認ID列名?你得到了什麼確切的錯誤? –

+0

詳細闡述了表格架構 –

+0

其默認的id列名稱。一個int作爲主鍵。我沒有得到任何錯誤,我等了2-3分鐘,然後什麼也沒有。 –

回答

0

嘗試Address模型來改變你的關係

$this->hasOne('App\Webshop', 'Adresse', 'Adresse'); 

Webshop模型

$this->belongsTo('App\Address', 'Adresse', 'Adresse'); 

編輯

我們檢索的關係,你可以做

$webshop = App\Address::find($id)->webshop; 
$address = App\Webshop::find($id)->address 
+0

與限制命令App \ Adress :: where('webshop) - >限制(10) - > get()'工作。當我使用這個命令'App \ Adress :: where('webshop) - > get()'tinkes凍結2-3min並且什麼也不做,沒有錯誤沒有結果只是一個新的行,我可以把我的命令放在cmd中 –

+0

I認爲你應該閱讀Laravel文檔。您不能在關係中創建'where'子句,而是使用['whereHas()'](https://laravel.com/docs/5.4/eloquent-relationships#querying-relationship-existence)方法。檢查我的和編輯 – Desh901

+0

然後,您正在定義一對一的關係。 'App \ Address :: find($ id) - > webshop'將只返回一個元素 – Desh901

0

請這個嘗試 -

use App\Adress; 
use App\Webshop; 

$result = Webshop::with('Adress')->where('Webshop.id',$id)->get(); 
or 
$result = Adress::with('Webshop')->where('Adress.id',$id)->get(); 

希望這將幫助你。