最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Laravel make a relationships with different column names - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a comment  | 

1 Answer 1

Reset to default 1

You 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']);
发布评论

评论列表(0)

  1. 暂无评论