我想不出如何在Eloquent中处理这个问题。我有一个多对多的关系,需要一对一的关系分配给它。
这是我以最简单的形式设计的基本数据库结构:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class Program
{
public static void Main()
{
var key = Encoding.ASCII.GetBytes("0123456789abcdef");//Change the key.
var data = Encrypt("Hello World",key);
var str = Decrypt(data, key);
Console.WriteLine(str);
}
public static byte[] Encrypt(string plaintext, byte[] key)
{
using(var desObj = Rijndael.Create())
{
desObj.Key = key;
desObj.Mode = CipherMode.CFB;
desObj.Padding = PaddingMode.PKCS7;
using(var ms = new MemoryStream())
{
//Append the random IV that was generated to the front of the stream.
ms.Write(desObj.IV, 0, desObj.IV.Length);
//Write the bytes to be encrypted.
using(CryptoStream cs = new CryptoStream(ms, desObj.CreateEncryptor(), CryptoStreamMode.Write))
{
var plainTextBytes = Encoding.UTF8.GetBytes(plaintext);
cs.Write(plainTextBytes, 0, plainTextBytes.Length);
}
return ms.ToArray();
}
}
}
public static string Decrypt(byte[] cyphertext, byte[] key)
{
using(MemoryStream ms = new MemoryStream(cyphertext))
using(var desObj = Rijndael.Create())
{
desObj.Key = key;
desObj.Mode = CipherMode.CFB;
desObj.Padding = PaddingMode.PKCS7;
//Read the IV from the front of the stream and assign it to our object.
var iv = new byte[16];
var offset = 0;
while(offset < iv.Length)
{
offset += ms.Read(iv, offset, iv.Length - offset);
}
desObj.IV = iv;
//Read the bytes to be decrypted
using(var cs = new CryptoStream(ms, desObj.CreateDecryptor(), CryptoStreamMode.Read))
using(var sr = new StreamReader(cs, Encoding.UTF8))
{
return sr.ReadToEnd();
}
}
}
}
每个帐户属于多个代理商。
每个代理商都属于多个帐户。
每个“Account_Agent”(多对多数据透视表)属于收费。
如何在Eloquent模型中定义第三个关系?
我希望能够像这样(或类似)访问“account_agent”费用:
ACCOUNTS: id
AGENTS: id
FEES: id
ACCOUNT_AGENT: account_id, agent_id, fee_id
谢谢,希望我的问题很明确。
答案 0 :(得分:2)
见这里:
https://laravel.com/docs/5.4/eloquent-relationships#many-to-many
向下滚动到定义自定义中间表模型
基本上你要做的就是定义一个这样的类:
class AccountAgent extends Illuminate\Database\Eloquent\Relations\Pivot
{
/**
* Many:1 relationship with Fee model
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function fee()
{
return $this->belongsTo(Fee::class);
}
}
然后,您在Account类中定义多个:多个关系,如下所示:
/**
* The agents that belong to the account.
*/
public function agents()
{
return $this->belongsToMany(Agent::class)->using(AccountAgent::class);
}
然后在你的代码中,而不是这个:
foreach ($account->agents as $agent) {
echo $agent->fee;
}
......这样做:
foreach ($account->agents as $agent) {
/** @var Fee $fee_object */
$fee_object = $agent->pivot->fee;
}
在该循环中,$ fee_object属于费用类(涵盖费用表的模型类),因此您可以echo $fee_object->fee_amount
或其他任何需要使用的列。