[英]How to retrieve data from one to one relationship in Laravel 5.4
我有兩個 MSSQL 表,所以我創建了兩個模型 [Adress] 和 [Webshop]。 兩個表中的外鍵都是 Adresse。
1.型號【地址】
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,移動設備在 [Webshop] 表中,地址在 [Adress] 表中。 我認為這是這兩個表之間的一對一關系。
在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
我想同時從這兩個表中檢索數據。 這可能與關系有關還是我不得不使用連接?
編輯:也許我的外鍵是錯誤的
請試試這個 -
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();
希望這會幫助你。
嘗試將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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.