WordPress has two tables named posts
and woocommerce_sessions
, and I want to connect these two tables in Laravel
using the models I created. The issue is that the woocommerce_sessions
table does not have an ID; it uses session_id
.
woocommerce_sessions
structure:
session_id -> Primary
session_key -> Index
session_value
session_expiry
posts
structure:
ID -> PrimaryIndex
post_author -> Index
post_date
post_date_gmt
post_content
post_title
...
The relationships I created are as follows:
WoocommerceSessions:
public function product(): BelongsTo
{
return $this->belongsTo(Post::class, 'session_id', 'ID');
}
Posts:
public function session(): BelongsTo
{
return $this->belongsTo(WoocommerceSessions::class, 'session_id', 'ID');
}
and getting query:
$product = $this->product()->find($c['product_id']); // return null
The output of this relationship is null, which is incorrect.
WordPress has two tables named posts
and woocommerce_sessions
, and I want to connect these two tables in Laravel
using the models I created. The issue is that the woocommerce_sessions
table does not have an ID; it uses session_id
.
woocommerce_sessions
structure:
session_id -> Primary
session_key -> Index
session_value
session_expiry
posts
structure:
ID -> PrimaryIndex
post_author -> Index
post_date
post_date_gmt
post_content
post_title
...
The relationships I created are as follows:
WoocommerceSessions:
public function product(): BelongsTo
{
return $this->belongsTo(Post::class, 'session_id', 'ID');
}
Posts:
public function session(): BelongsTo
{
return $this->belongsTo(WoocommerceSessions::class, 'session_id', 'ID');
}
and getting query:
$product = $this->product()->find($c['product_id']); // return null
The output of this relationship is null, which is incorrect.
Share Improve this question asked Feb 1 at 20:45 DolDurmaDolDurma 17.4k56 gold badges221 silver badges424 bronze badges1 Answer
Reset to default 1You need match the primary and foreign keys correctly in your models. Since woocommerce_sessions uses session_id as its primary key and posts uses ID, set the relationship like this in WoocommerceSessions:
public function post(){
return $this->belongsTo(Post::class, 'session_id', 'ID');
}
in Post
you can add:
public function woocommerceSession(){
return $this->hasOne(WoocommerceSessions::class, 'session_id', 'ID');
}
then if you want the product linked to a particular session:
$product = $this->post;
the ->find($c['product_id'])
on the relationship will return null unless the primary key aligns with that exact ID. to get a product by its ID:
$product = Post::find($c['product_id']);