【问题标题】:How to get foreign key from eloquent collection in laravel如何从 laravel 的 eloquent 集合中获取外键
【发布时间】:2021-09-08 14:08:49
【问题描述】:

我的用户模型中有 hasMany 关系;

 /**
 * Get the posts for the users.
 */
public function posts()
{
    return $this->hasMany(Posts::class); //foreign key assigned by user_id
}

我需要在 Eloquent 数据中获取一个外来 id

控制器;

use App\Models\User;

$posts = User::find(1)->posts;

foreach ($posts as $post) {
    //
}
//for example
$foreign_key = $posts->foreign_key;
echo "all posts collection assigned foreign key is; ".$foreign_key;

预期输出;

1

如何获取外键?

【问题讨论】:

    标签: php mysql laravel eloquent eloquent-relationship


    【解决方案1】:

    您可以执行以下操作。由于帖子具有hasmany 关系,因此即使您在帖子中有一项,它也会返回对象集合。

    foreach ($posts as $post) {
         
        echo $post->user_id;
    }
    

     dd($posts->first()->user_id);
    

    如果您仍然需要帖子关系中的一项,则可以添加一项关系

    public function post()
    {
        return $this->hasOne(Posts::class); //foreign key assigned by user_id
    }
    

    然后你就可以访问了

    $posts = User::find(1)->post;
    
    $foreign_key =$posts->user_id;
    

    【讨论】:

    • 我没有使用每个,你的第二个建议dd($posts->first()->user_id); 很好,但我得到了“尝试获取非对象的属性'user_id'”错误。有时表没有任何记录。
    • 尝试添加条件 if($post=$posts->first()){ dd($post->user_id); )
    • 是的,您只能在其有关系或不能直接做的情况下做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 2022-01-20
    • 2021-07-10
    • 2016-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多